class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { vector<int> r(2, -1); if (!nums.size()) { return r;//为空时,返回[-1,-1] } int l = 0, h = nums.size() - 1, m = 0; if (target < nums[l] || nums[h] < target) { return r; //小于最小或大于最大返回[-1,-1] } while (l <= h) { m = (l + h) / 2; if (nums[m] == target) { //命中m时 int i = m; while (nums[i] == target&&i < nums.size()) { i++;//寻找nums中与target相等值的右界 } r[1] = i - 1; while (nums[m] == target&&m >= 0) { m--;//寻找nums中与target相等值的左界 } r[0] = m + 1; return r; } else if (nums[m] < target) { l = m + 1; } else { h = m - 1; } } return r;//没找到target,返回[-1,-1] } };
补充一个python的实现:
1 class Solution: 2 def searchRange(self, nums: 'List[int]', target: 'int') -> 'List[int]': 3 n = len(nums) 4 i = 0 5 j = n - 1 6 if i == j: 7 if nums[i] == target: 8 return [0,0] 9 else: 10 return [-1,-1] 11 begin = 0 12 end = n - 1 13 while i < j: 14 if nums[i] == target: 15 begin = i 16 end = i 17 while end < n and nums[end] == target: 18 end += 1 19 return [begin,end-1] 20 if nums[j] == target: 21 end = j 22 begin = j 23 while begin >= 0 and nums[begin] == target: 24 begin -= 1 25 return [begin+1,end] 26 mid = i + (j - i) // 2 27 if nums[mid] == target: 28 begin = mid 29 while begin >= 0 and nums[begin] == target: 30 begin -= 1 31 end = mid 32 while end < n and nums[end] == target: 33 end += 1 34 return [begin+1,end-1] 35 elif nums[mid] < target: 36 i = mid + 1 37 else: 38 j = mid - 1 39 return [-1,-1] 40 41