Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm‘s runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1]
.
For example,
Given [5, 7, 7, 8, 8, 10]
and target value 8,
return [3, 4]
.
用binary search轻松解决,search for a range 等同于search for the first/last appearance,只需对常规的binary search 稍作改动,不要一看到等于target就返回index,而是应该根据找first/last来判断是否还要继续做binary search (ex.寻找first appearance时,如果nums[mid] >= target都应该继续binary search,因为找到的index并不一定是first appearance,应该进一步向前寻找直到跳出循环,还应优先判断nums[start]==target是否成立来决定first index)
1. java
public class Solution { public int[] searchRange(int[] nums, int target) { if(nums == null){ return new int[]{-1,-1}; } int start = 0; int end = nums.length - 1; while(start + 1 < end){ int mid = start + (end - start)/2; if(nums[mid] < target){ start = mid; } else if(nums[mid] >= target){ end = mid; } } int[] result = new int[2]; if(nums[start] == target){ result[0] = start; } else if(nums[end] == target){ result[0] = end; } else { return new int[]{-1,-1}; } start = 0; end = nums.length - 1; while(start + 1 < end){ int mid = start + (end - start)/2; if(nums[mid] <= target){ start = mid; } else if(nums[mid] > target){ end = mid; } } if(nums[end] == target){ result[1] = end; return result; } else if(nums[start] == target){ result[1] = start; return result; } return new int[]{-1,-1}; } }
2.Python
class Solution: """ @param A : a list of integers @param target : an integer to be searched @return : a list of length 2, [index1, index2] """ def searchRange(self, A, target): # write your code here result = [-1,-1] if A is None or len(A) == 0: return result start = 0 end = len(A) - 1 while(start + 1 < end): mid = start + (end - start)/2 if A[mid] >= target: end = mid elif A[mid] < target: start = mid if A[start] == target: result[0] = start elif A[end] == target: result[0] = end else: return result start = 0 end = len(A) - 1 while(start + 1 < end): mid = start + (end - start)/2 if A[mid] > target: end = mid elif A[mid] <= target: start = mid if A[end] == target: result[1] = end return result elif A[start] == target: result[1] = start return result return result
时间: 2024-11-04 13:18:31