-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFindFirstandLastPositionofElementinSortedArray_34.cpp
67 lines (51 loc) · 1.58 KB
/
FindFirstandLastPositionofElementinSortedArray_34.cpp
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
/*
~ Author : leetcode.com/tridib_2003/
~ Problem : 34. Find First and Last Position of Element in Sorted Array
~ Link : https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
*/
class Solution {
private:
int findFirstOccurrenceIndex(vector<int> &nums, int target) {
int low = 0, high = nums.size() - 1, idx = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (nums[mid] == target) {
idx = mid;
high = mid - 1;
}
else if (nums[mid] < target) {
low = mid + 1;
}
else {
high = mid - 1;
}
}
return idx;
}
int findLastOccurrenceIndex(vector<int> &nums, int target) {
int low = 0, high = nums.size() - 1, idx = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (nums[mid] == target) {
idx = mid;
low = mid + 1;
}
else if (nums[mid] < target) {
low = mid + 1;
}
else {
high = mid - 1;
}
}
return idx;
}
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> res {-1, -1};
res[0] = findFirstOccurrenceIndex(nums, target);
if (res[0] == -1)
return res;
res[1] = findLastOccurrenceIndex(nums, target);
return res;
}
};