-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfirst and last position of an element.cpp
57 lines (52 loc) · 1.29 KB
/
first and last position of an element.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
class Solution {
public:
int leftIndex(vector<int> nums, int target){
int start = 0;
int end = nums.size()-1;
int mid = start + (end-start)/2;
int result=-1;
while(start <= end) {
if(nums[mid] == target) {
result= mid;
end = mid-1;
}
else if(target > nums[mid]) {
start = mid + 1;
}
else{
end = mid - 1;
}
mid = start + (end-start)/2;
}
return result;
}
//Right Index
int rightIndex(vector<int> nums, int target){
int start = 0;
int end = nums.size()-1;
int mid = (end+start)/2;
int result=-1;
while(start <= end) {
if(nums[mid] == target) {
result= mid;
start = mid+1;
}
else if(target > nums[mid]) {
start = mid + 1;
}
else{
end = mid - 1;
}
mid = start + (end-start)/2;
}
return result;
}
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> Answer;
int LeftMost = leftIndex(nums,target);
Answer.push_back(LeftMost);
int RightMost = rightIndex(nums,target);
Answer.push_back(RightMost);
return Answer;
}
};