经典面试题二分查找,当年校招面试经常遇到,先用最简单最直接的方法AC。

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int start = 0,end = nums.size() - 1;
        while(start <= end)
        {
            int mid = (start + end) / 2;
            if(nums[mid] == target)
                return mid;
            else if(nums[mid] < target)
                start = mid + 1;
            else
                end = mid - 1;
        }
        
        return -1;
    }
};

运行结果相对一般,仅击败63%用户。

Runtime: 72 ms, faster than 63.29% of C++ online submissions for Binary Search.
Memory Usage: 27.8 MB, less than 99.96% of C++ online submissions for Binary Search.

上面的代码其实存在溢出风险,当每次查询都执行到逻辑mid = mid + 1时,此时start + end有可能溢出,优化逻辑为mid = start + (end -start)/2;

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int start = 0,end = nums.size() - 1;
        while(start <= end)
        {
            int mid = start + (end - start) / 2;
            if(nums[mid] == target)
                return mid;
            else if(nums[mid] < target)
                start = mid + 1;
            else
                end = mid - 1;
        }
        
        return -1;
    }
};

运行结果:

Runtime: 64 ms, faster than 92.65% of C++ online submissions for Binary Search.
Memory Usage: 27.7 MB, less than 99.96% of C++ online submissions for Binary Search.