0%

704.二分查找

704. 二分查找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int search(vector<int>& nums, int target) {
int left=0;
int right=nums.size()-1;
while(left<=right){
int middle=(left+right)/2;
if (nums[middle]>target){
right=middle-1;
}
else if (nums[middle]<target){
left=middle+1;
}
else{
return middle;
}

}
return -1;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int search(int* nums, int numsSize, int target){

int left=0;
int right=numsSize-1;
while(left<=right){
int middle=(left+right)/2;
if (nums[middle]>target){
right=middle-1;
}
else if (nums[middle]<target){
left=middle+1;
}
else{
return middle;
}

}
return -1;

}
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
#include<iostream>
#include<vector>
using namespace std;
int main(){
vector <int> nums;
int n;
cin>>n;
int target;
cin>>target;
while(n--){
int temp;
cin>>temp;
nums.push_back(temp);
}
int left=0;
int right=nums.size()-1;
while(left<=right){
int middle=(left+right)/2;
if(nums[middle]>target){
right=middle-1;
}
else if(nums[middle]<target){
left=middle+1;
}
else {
cout<<middle;
break;
}


}

return 0;
}
-------------本文结束感谢您的阅读-------------
老板你好,讨口饭吃