题解 | #二分查找-I#(3种方法)
二分查找-I
http://www.nowcoder.com/practice/d3df40bd23594118b57554129cadf47b
class Solution {
public:
int search(vector<int>& nums, int target) {
int len = nums.size();
int left=0, right=len-1;
while(left <= right){
mid = left+(right-left >> 1); // +-大于位移运算的优先级 左移*2
if(nums[mid] == target) return mid;
if(nums[mid] < target) left = mid+1;
if(nums[mid] > target) right = mid-1;
}
return -1;
}
};
class Solution {
public:
int search(vector<int>& nums, int target) {
int right = nums.size();
if(right==0) return -1;
int left = 0;
while(left < right){
int mid = left + right >>1;
nums[mid]<target?left=mid+1:right=mid; // lleft为找到的大于等于target的下标
}
return nums[left]==target?left:-1;
}
};
class Solution {
public:
int search(vector<int>& nums, int target) {
int right = nums.size();
if(right==0) return -1;
int ans = upper_bound(nums.begin(), nums.end(), target) - nums.begin() - 1;
return nums[ans]==target?ans:-1;
}
};