Problem Link: https://leetcode.com/problems/binary-search/
Binary Search - LeetCode
Can you solve this real interview question? Binary Search - Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
leetcode.com
Solution 1. Binary Search
Time: $O(\text{log } N)$
Space: $O(1)$
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if target < nums[0] or target > nums[len(nums) - 1]: return -1
lo = 0; hi = len(nums) - 1
while lo < hi:
mid = lo + (hi - lo) // 2
if nums[mid] < target:
lo = mid + 1
else:
hi = mid
return lo if nums[lo] == target else -1
'Problem Solving' 카테고리의 다른 글
[Leetcode] 235. Lowest Common Ancestor of a Binary Search Tree (0) | 2023.07.18 |
---|---|
[Leetcode] 733. Flood Fill (0) | 2023.07.18 |
[Leetcode] 242. Valid Anagram (0) | 2023.07.13 |
[Leetcode] 226. Invert Binary Tree (0) | 2023.07.13 |
[Leetcode] 125. Valid Palindrome (0) | 2023.07.12 |