1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| #include<vector>
using namespace std;
int search(vector<int>& nums, int target) {
int i = 0, j = nums.size()-1; //这里的类型别用auto, 否则后续
//mid - 1 可能溢出
int mid;
while (i <= j) {
mid = (i + j ) / 2;
if (nums[mid] == target) {
return mid;
}else if (nums[mid] > target) j = mid-1; //注意此处 -1
else i = mid+1; //以及此处 + 1
//否则容易陷入死循环
}
return -1;
}
|