1
+ /*
2
+ Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.
3
+
4
+ If target is not found in the array, return [-1, -1].
5
+
6
+ You must write an algorithm with O(log n) runtime complexity.
7
+
8
+
9
+
10
+ Example 1:
11
+
12
+ Input: nums = [5,7,7,8,8,10], target = 8
13
+ Output: [3,4]
14
+ Example 2:
15
+
16
+ Input: nums = [5,7,7,8,8,10], target = 6
17
+ Output: [-1,-1]
18
+ Example 3:
19
+
20
+ Input: nums = [], target = 0
21
+ Output: [-1,-1]
22
+
23
+
24
+ Constraints:
25
+
26
+ 0 <= nums.length <= 105
27
+ -109 <= nums[i] <= 109
28
+ nums is a non-decreasing array.
29
+ -109 <= target <= 109
30
+
31
+ */
32
+ #include < bits/stdc++.h>
33
+ class Solution {
34
+ public:
35
+ int get_index (vector<int >& nums, int target, bool found){
36
+ int ans = -1 ;
37
+ int start = 0 , end = nums.size () - 1 ;
38
+ while (start <= end){
39
+ int mid = start + (end - start) / 2 ;
40
+ if (nums[mid] == target){
41
+ ans = mid;
42
+ if (found){
43
+ end = mid - 1 ; // search in left part
44
+ }
45
+ else {
46
+ start = mid + 1 ; // search in right part
47
+ }
48
+ }
49
+ else if (nums[mid] > target){
50
+ end = mid - 1 ;
51
+ }
52
+ else {
53
+ start = mid + 1 ;
54
+ }
55
+ }
56
+ return ans;
57
+ }
58
+ vector<int > searchRange (vector<int >& nums, int target) {
59
+ vector<int > ans (2 , -1 );
60
+ int first = get_index (nums, target, true );
61
+ if (first == -1 )
62
+ return ans;
63
+ int last = get_index (nums, target, false );
64
+ // ans.push_back(first);
65
+ // ans.push_back(last);
66
+ ans[0 ] = first;
67
+ ans[1 ] = last;
68
+ return ans;
69
+ }
70
+ };
0 commit comments