Leetcode: 704. Binary Search

思路:

将index不断除以2以找到对应的值,while条件是在index保持在>=0 && < array size

 

思路修正:

因为不断地根据寻找的边界限缩,所以index不可能超出前面说的两个範围,因此乾脆改成执行for迴圈 log(n)次,并将初始lower bound设为0,upper bound设为array size。

 

在修正:

还是不对,所以改成用lb, ub去判定。

 
 
 

程式

class Solution {public:    int search(vector<int>& nums, int target) {        int ans = -1;        int lb = 0, ub = nums.size() - 1;        while(lb <= ub) {            //cout << "(" << lb << ", " << ub <<  ", " << index << ")";            int index = lb + (ub - lb) / 2;            if ( nums[index] < target )                 lb = index + 1;            else if ( nums[index] > target )                ub = index - 1;            else {                ans = index;                break;            }        }        return ans;    }};

 
 

后来

有遇到ERROR: AddressSanitizer: heap-buffer-overflow on address
原因是upper bound 不应该使用arrary size,而是要使用最大index,即array size - 1

 
 

参考

https://zh.wikipedia.org/wiki/二分搜寻演算法


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章