[LeetCode] 34. Find First and Last Position of Element in Sorted Array == [LintCode] 61. Search for a Range_Easy tag: Binary Search
2018-08-29 10:06 Johnson_强生仔仔 阅读(266) 评论(0) 编辑 收藏 举报
Description
Given a sorted array of n integers, find the starting and ending position of a given target value.
If the target is not found in the array, return [-1, -1]
.
Example
Given [5, 7, 7, 8, 8, 10]
and target value 8
,
return [3, 4]
.
Challenge
O(log n) time.
这个题目的思路就是用两个binary search, 分别求first index 和last index.
Code 其实可以利用helper funciton来去优化code.
class Solution: def searchRange(self, A, target): # write your code here if not A: return [-1,-1] l, r , ans = 0, len(A) -1, [-1,-1] while l + 1 < r: mid = l + (r - l)//2 if A[mid] < target: l = mid elif A[mid] > target: r = mid else: r = mid if A[l] == target: ans[0] = l elif A[r] == target: ans[0] = r else: return ans # find last index l, r = 0, len(A) -1 while l + 1 < r: mid = l + (r - l)//2 if A[mid] < target: l = mid elif A[mid] > target: r = mid else: l = mid if A[r] == target: ans[1] = r elif A[l] == target: ans[1] = l else: return ans return ans
去掉不必要的行
class Solution: def searchRange(self, A, target): # write your code here if not A: return [-1,-1] l, r , ans = 0, len(A) -1, [-1,-1] while l + 1 < r: mid = l + (r - l)//2 if A[mid] < target: l = mid else: r = mid if A[l] == target: ans[0] = l elif A[r] == target: ans[0] = r else: return ans # find last index l, r = 0, len(A) -1 while l + 1 < r: mid = l + (r - l)//2 if A[mid] <= target: l = mid else: r = mid if A[r] == target: ans[1] = r elif A[l] == target: ans[1] = l return ans
Use helper function to make the code even shorter.
class Solution: def searchRange(self, A, target): l, r = 0, len(A) - 1 if not A or nums[l] > target or nums[r] < target: return [-1, -1] def helper(points, pos, target): while points[0] + 1 < points[1]: mid = points[0] + (points[1] - points[0])//2 if A[mid] > target: points[1] = mid elif A[mid] < target: points[0] = mid else: points[pos] = mid if A[points[1 - pos]] == target: return points[1 - pos] if A[points[pos]] == target: return points[pos] return -1 return [helper([l, r], 1, target), helper([l, r], 0, target)]