-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfind_first_last.cpp
59 lines (55 loc) · 1.51 KB
/
find_first_last.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
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int low=0,high=nums.size()-1;
//寻找第一次出现的位置
int first=-1;
while(low<=high){
int mid=(low+high)/2;
if (mid==0 && nums[mid]==target){
first=mid;
break;
}
else if (nums[mid]==target && nums[mid-1]!=target) {
first=mid;
break;
}
else if (nums[mid]>=target) high=mid-1;
else if (nums[mid]<=target) low=mid+1;
}
int last=-1;
low=0,high=nums.size()-1;
while(low<=high){
int mid=(low+high)/2;
//cout<<"mid="<<mid<<endl;
if (mid==nums.size()-1 && nums[mid]==target){
// cout<<"first\n";
last=mid;
break;
}
else if (nums[mid]==target && nums[mid+1]!=target){
last=mid;
//cout<<"second\n";
break;
}
else if (nums[mid]<=target) low=mid+1;
else if (nums[mid]>=target) high=mid-1;
}
vector<int> vec;
vec.push_back(first);
vec.push_back(last);
// cout<<first<<' '<<last<<endl;
return vec;
}
};
int main(){
vector<int> vec={3};
Solution sol;
sol.searchRange(vec,3);
}