704. 二分查找

C++

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