1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
| class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { vector<int> result = {-1, -1}; int low = 0, high = nums.size() - 1; int mid, midvalue; bool flag = false; while(low <= high) { mid = low + (high - low) / 2; midvalue = nums[mid]; if(midvalue == target) {flag = true; break;} if(midvalue < target) low = mid + 1; if(midvalue > target) high = mid - 1; } if(!flag) return result; else { int left = -1, right = -1; int leftlow = 0, lefthigh = mid; int rightlow = mid, righthigh = nums.size() - 1; int leftmid, leftmidvalue; int rightmid, rightmidvalue; while(leftlow <= lefthigh) { leftmid = leftlow + (lefthigh - leftlow) / 2; leftmidvalue = nums[leftmid]; if(leftmidvalue == target) { if(leftmid == 0) {left = leftmid; break;} if(leftmid > 0) { if(nums[leftmid - 1] < target) {left = leftmid; break;} else lefthigh = leftmid - 1; } } if(leftmidvalue < target) leftlow = leftmid + 1; } while(rightlow <= righthigh) { rightmid = rightlow + (righthigh - rightlow) / 2; rightmidvalue = nums[rightmid]; if(rightmidvalue == target) { if(rightmid == nums.size() - 1) {right = rightmid; break;} if(rightmid < nums.size() - 1) { if(nums[rightmid + 1] > target) {right = rightmid; break;} else rightlow = rightmid + 1; } } if(rightmidvalue > target) righthigh = rightmid - 1; } result[0] = left; result[1] = right; } return result; } };
class Solution { public: int binarySearch(vector<int>& nums, int target, bool lower) { int left = 0, right = (int)nums.size() - 1, ans = (int)nums.size(); while (left <= right) { int mid = (left + right) / 2; if (nums[mid] > target || (lower && nums[mid] >= target)) { right = mid - 1; ans = mid; } else { left = mid + 1; } } return ans; }
vector<int> searchRange(vector<int>& nums, int target) { int leftIdx = binarySearch(nums, target, true); int rightIdx = binarySearch(nums, target, false) - 1; if (leftIdx <= rightIdx && rightIdx < nums.size() && nums[leftIdx] == target && nums[rightIdx] == target) { return vector<int>{leftIdx, rightIdx}; } return vector<int>{-1, -1}; } };
|