-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution01.cpp
43 lines (39 loc) · 1.02 KB
/
Solution01.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
// Leetcode: https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int start = 0, end = nums.size()-1, first = -1, last = -1, mid;
while(start<=end)
{
mid = start + (end - start)/2;
if(nums[mid]==target)
{
first=mid;
end=mid-1;
}
else if(nums[mid]<target)
start=mid+1;
else
end=mid-1;
}
// Last Element
start = 0, end = nums.size()-1;
while(start<=end)
{
mid = start + (end - start)/2;
if(nums[mid]==target)
{
last=mid;
start=mid+1;
}
else if(nums[mid]<target)
start=mid+1;
else
end=mid-1;
}
vector<int>a(2);
a[0]=first;
a[1]=last;
return a;
}
};