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
| int getFirst(vector<int>& nums, int target, int left, int right) { if (left > right) return -1; int mid = (right + left) / 2; if (nums[mid] == target) { if (mid == 0 || mid > 0 && nums[mid-1] != target) { return mid; } else return getFirst(nums, target, left, mid - 1); } else if (nums[mid] > target) { return getFirst(nums, target, left, mid - 1); } else { return getFirst(nums, target, mid + 1, right); } }
int getLast(vector<int>& nums, int target, int left, int right) { if (left > right) return -1; int mid = (right + left) / 2; if (nums[mid] == target) { if (mid == nums.size() - 1 || nums[mid+1] != target) { return mid; } else return getLast(nums, target, mid + 1, right); } else if (nums[mid] > target) { return getLast(nums, target, left, mid - 1); } else { return getLast(nums, target, mid + 1, right); } }
int search(vector<int>& nums, int target) { if (nums.size() < 1) return 0; int left = getFirst(nums, target, 0, nums.size() - 1); int right = getLast(nums, target, 0, nums.size() - 1); if (left >= 0 && right >= 0) return right - left + 1; return 0; }
|