一次过
1 class Solution { 2 public: 3 vector<int> searchRange(int A[], int n, int target) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 int left = 0; 7 int right = n-1; 8 while (left <= right) { 9 int mid = (left+right)/2; 10 if (target == A[mid]) { 11 int l, r; 12 l = r = 0; 13 while (A[mid] == A[mid-l]) l++; 14 while (A[mid] == A[mid+r]) r++; 15 vector<int> ret; 16 ret.push_back(mid-l+1); 17 ret.push_back(mid+r-1); 18 return ret; 19 } 20 if (target > A[mid]) left = mid+1; 21 else right = mid-1; 22 } 23 return {-1, -1}; 24 } 25 };
C#
1 public class Solution { 2 public int[] SearchRange(int[] nums, int target) { 3 int left = 0; 4 int right = nums.Length - 1; 5 int[] ans = new int[2]; 6 while (left <= right) { 7 int mid = (left + right) / 2; 8 if (target == nums[mid]) { 9 int l = 0, r = 0; 10 while (mid - l >= 0 && nums[mid] == nums[mid-l]) l++; 11 while (mid + r < nums.Length && nums[mid] == nums[mid+r]) r++; 12 ans[0] = mid - l + 1; 13 ans[1] = mid + r - 1; 14 return ans; 15 } 16 if (target > nums[mid]) left = mid + 1; 17 else right = mid - 1; 18 } 19 ans[0] = ans[1] = -1; 20 return ans; 21 } 22 }