Add solution for neetcode: binary search
This commit is contained in:
parent
e37b949c18
commit
64108ba422
2 changed files with 45 additions and 0 deletions
21
neetcode/arrays/binary_search/README.md
Normal file
21
neetcode/arrays/binary_search/README.md
Normal file
|
@ -0,0 +1,21 @@
|
|||
Binary Search
|
||||
You are given an array of distinct integers nums, sorted in ascending order, and an integer target.
|
||||
|
||||
Implement a function to search for target within nums. If it exists, then return its index, otherwise, return -1.
|
||||
|
||||
Your solution must run in O(logn) time.
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: nums = [-1,0,2,4,6,8], target = 4
|
||||
|
||||
Output: 3
|
||||
Example 2:
|
||||
|
||||
Input: nums = [-1,0,2,4,6,8], target = 3
|
||||
|
||||
Output: -1
|
||||
Constraints:
|
||||
|
||||
1 <= nums.length <= 10000.
|
||||
-10000 < nums[i], target < 10000
|
24
neetcode/arrays/binary_search/solution.py
Normal file
24
neetcode/arrays/binary_search/solution.py
Normal file
|
@ -0,0 +1,24 @@
|
|||
from typing import List
|
||||
|
||||
|
||||
class Solution:
|
||||
def search(self, nums: List[int], target: int) -> int:
|
||||
left = 0
|
||||
right = len(nums) - 1
|
||||
while left <= right:
|
||||
mid = (right + left) // 2
|
||||
if target < nums[mid]:
|
||||
right = mid - 1
|
||||
elif target > nums[mid]:
|
||||
left = mid + 1
|
||||
else:
|
||||
return mid
|
||||
return -1
|
||||
|
||||
|
||||
s = Solution()
|
||||
# nums = [-1, 0, 2, 4, 6, 8]
|
||||
# print(s.search(nums, 4))
|
||||
# print(s.search(nums, 3))
|
||||
nums = [-1, 0, 3, 5, 9, 12]
|
||||
print(s.search(nums, 9))
|
Loading…
Reference in a new issue