题解 | #二分查找-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;
    }
};
全部评论

相关推荐

10-24 11:10
山西大学 Java
若梦难了:哥们,面试挂是很正常的。我大中厂终面挂,加起来快10次了,继续努力吧。
点赞 评论 收藏
分享
2 1 评论
分享
牛客网
牛客企业服务