if nums[end] == target: return end elif nums[start] == target: return start else: return-1
Python代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
deflast_position(self, nums: List[int], target: int) -> int: ifnot nums: return-1 start, end = 0, len(nums) - 1 while start + 1 < end: mid = start + (end - start) // 2 if target < nums[mid]: end = mid elif target > nums[mid]: start = mid else: # Depends on the target on the right side or left side. For fist pos, use end = mid start = mid
if nums[end] == target: return end elif nums[start] == target: return start else: return-1
Python代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
deffirst_position(self, nums: List[int], target: int) -> int: ifnot nums: return-1 start, end = 0, len(nums) - 1 while start + 1 < end: mid = start + (end - start) // 2 if target < nums[mid]: end = mid elif target > nums[mid]: start = mid else: end = mid
if nums[start] == target: return start elif nums[end] == target: return end else: return-1
Python代码:
如果是smaller_or_equal_position,Line 13和15取等号
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
defsmaller_position(self, nums: List[int], target: int) -> int: ifnot nums: return-1 start, end = 0, len(nums) - 1 while start + 1 < end: mid = start + (end - start) // 2 if target > nums[mid]: start = mid elif target < nums[mid]: end = mid else: end = mid if nums[end] < target: # nums[end] <= target for smaller_or_equal_position return end if nums[start] < target: # nums[start] < target for smaller_or_equal_position return start return-1
Python代码:
如果是greater_or_equal_position,Line 13和15取等号
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
defgreater_position(self, nums: List[int], target: int) -> int: ifnot nums: return-1 start, end = 0, len(nums) - 1 while start + 1 < end: mid = start + (end - start) // 2 if target > nums[mid]: start = mid elif target < nums[mid]: end = mid else: start = mid if nums[start] > target: # nums[start] >= target for greater_or_equal_position return start if nums[end] > target: # nums[end] >= target for greater_or_equal_position return end return-1
找峰值
注意事项:
判断mid+1的元素不越界
最后返回start和end之中较大者
Python代码:
1 2 3 4 5 6 7 8 9 10 11
deffind_peak(self, nums: List[int]) -> int: ifnot nums: return-1 start, end = 0, len(nums) - 1 while start + 1 < end: mid = start + (end - start) // 2 if mid + 1 <= end and nums[mid] < nums[mid + 1]: start = mid else: end = mid return start if nums[start] > nums[end] else end