leetcode_704二分查找

一、题目

 

 二、思考方法

   2.1 偷懒方法

   最偷懒的方法是直接使用数组的查找函数

class Solution {
public:
    int search(vector<int>& nums, int target) {
        vector<int>::iterator result_loc = find(nums.begin(), nums.end(), target);
        if (result_loc == nums.end()){
            return -1;
        }
        else{
            return result_loc-nums.begin();
        }
    }
};

 效果如下:

     2.2二分法

 二分法其实就是不断比较,然后缩小区间范围,从而加快查找。

   

class Solution {
public:
    int search(vector<int>& nums, int target) {
        //二分查找
        int length = nums.size();
        if(length==1){
            if(nums[0]==target) 
                return 0;
            else
                return -1; 
        }
        int start_loc = 0;
        int end_loc = length;
        int middle_loc;
        while(end_loc-start_loc>1)
        {
            middle_loc = start_loc + (end_loc-start_loc)/2;
            if(nums[middle_loc] == target)
            {
                return middle_loc;
            }
            else if(nums[middle_loc] > target)
            {
                end_loc = middle_loc;
            }
            else
                start_loc = middle_loc;    
        }
        if(nums[start_loc] == target)
            return start_loc;
        else
            return -1;
    }
};

 代码效果如下:

 

 有一个很有意思的现象是,当我把循环里面第一个判断语句移动到最后一个的时候,会极大的影响运行时间。

 目前的方法虽然时间上还行,但是不知道为什么内存消耗上太大。

3 参考代码

  别人差不多也是这个思路,只不过是选取的区间差了一个值。

代码如下

class Solution {
public:
    int search(vector<int>& nums, int target) {
        //二分查找
        int length = nums.size();
        if(length==1){
            if(nums[0]==target) 
                return 0;
            else
                return -1; 
        }
        int start_loc = 0;
        int end_loc = length-1;
        int middle_loc = 0;
        while(end_loc-start_loc>=0)
        {
            middle_loc = start_loc + (end_loc-start_loc)/2;
            if(nums[middle_loc] == target)
            {
                return middle_loc;
            }
            else if(nums[middle_loc] > target)
            {
                end_loc = middle_loc-1;
            }
            else
                start_loc = middle_loc+1;    
        }
        return -1;
    }
};

性能如下:

 

 这个性能只能作为一个参考,因为即使是同一个代码,多次运行,得到的结果也不一样。

posted @ 2021-11-02 10:22  星光夜  阅读(27)  评论(0)    收藏  举报