Description
Binary search is a famous question in algorithm. For a given sorted array (ascending order) and a target number, find the first index of this number in O(log n) time complexity. If the target number does not exist in the array, return -1.
Example If the array is [1, 2, 3, 3, 4, 5, 10], for given target 3, return 2.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
class Solution: # @param nums: The integer array # @param target: Target number to find # @return the first position of target in nums, position start from 0 def binarySearch(self, nums, target): if len(nums) == 0: return -1 start, end = 0, len(nums) - 1 while start + 1 < end: mid = (start + end) / 2 if nums[mid] < target: start = mid else: end = mid if nums[start] == target: return start if nums[end] == target: return end return -1 |
Problem Set
Search Insert Position
DescriptionSolutionNote
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume NO duplicates in the array.
Example:
[1,3,5,6]
, 5 → 2[1,3,5,6]
, 2 → 1[1,3,5,6]
, 7 → 4[1,3,5,6]
, 0 → 0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
class Solution: """ @param A : a list of integers @param target : an integer to be inserted @return : an integer """ def searchInsert(self, A, target): if not A: return 0 start, end = 0, len(A)-1 while start + 1 < end: mid = (start + end) / 2 if A[mid] < target: start = mid else: end = mid if A[start] >= target: return start if A[end] >= target: return end return len(A) |
1 2 3 4 5 6 7 8 9 |
# Another version for search() # in this version, make a copy of clist at the begining, and modify it for next node # in previous version, make a copy of clist when invoke search() for each next node def search(self, ans, clist, nums, pos): ans.append(list(clist)) for i in range(pos, len(nums)): clist.append(nums[i]) self.search(ans, clist, nums, i+1) clist(-1) |
Submit a Comment