vector<int> searchRange1(vector<int>& nums, int target){ int first = 0,last = nums.size() - 1,mid; vector<int> ret{-1,-1}; while(first <= last) { mid = (first + last)/2; if (nums[mid] == target){ break; } elseif (nums[mid] < target) first = mid+1; else last = mid - 1; }
int l = mid,f = mid; ret[0] = first; ret[1] = last;
while(first <= l) { int m = (first + l)/2; if (nums[m] == nums[mid]) l = m - 1; elseif (nums[m+1] != nums[mid]) first = m + 1; else { ret[0] = m+1; break; } } while(f <= last) { int m = (f + last)/2; if (nums[m] == nums[mid]) f = m + 1; elseif (nums[m-1] != nums[mid]) last = m - 1; else { ret[1] = m - 1; break; } }
vector<int> searchRange(int A[], int n, int target){ int i = 0, j = n - 1; vector<int> ret(2, -1); // Search for the left one while (i < j) { int mid = (i + j) /2; if (A[mid] < target) i = mid + 1; else j = mid; } if (A[i]!=target) return ret; else ret[0] = i;
// Search for the right one j = n-1; // We don't have to set i to 0 the second time. while (i < j) { int mid = (i + j) /2 + 1;// Make mid biased to the right if (A[mid] > target) j = mid - 1; else i = mid;// So that this won't make the search range stuck. } ret[1] = j; return ret; }