-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFirst1_BinarySearch.cpp
More file actions
74 lines (70 loc) · 1.64 KB
/
First1_BinarySearch.cpp
File metadata and controls
74 lines (70 loc) · 1.64 KB
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
68
69
70
71
72
73
74
// Forward declaration of isBadVersion API.
bool isBadVersion(int version);
class Solution {
public:
int firstBadVersion(int n) {
int start=1,end=n,mid;
while(start<end)
{
mid = start + (end-start)/2;
if(isBadVersion(mid)==false)
start=mid+1;
else
end=mid;
}
return start;
}
};
// Forward declaration of guess API.
// @param num, your guess
// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
int guess(int num);
class Solution {
public:
int guessNumber(int n) {
int start=1,end=n,mid;
while(start<end)
{
mid=start + (end-start)/2;
if((guess(mid)==1))
{
start=mid+1;
}
else
end=mid;
}
return start;
}
};
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int left=0,right=nums.size(),mid;
vector<int>v;
int start=findfirst(nums,target);
if((start==right) || (nums[start]!=target))
{
v.push_back(-1);
v.push_back(-1);
return v;
}
else
v.push_back(start);
int end=findfirst(nums,target+1)-1;
v.push_back(end);
return v;
}
int findfirst(vector<int>& nums, int target)
{
int low=0,high=nums.size(),mid;
while(low<high)
{
mid=low + (high-low)/2;
if(nums[mid]<target)
low=mid+1;
else
high=mid;
}
return low;
}
};