Leetcode (Algorithm I): 5. Search Insert Position

思路

也是binary search的应用题,承前两篇文章,有lb跟ub和index三个数值可选,我目前觉得应该是回传lower bound值。

 
 

程式

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

 
 

但我

解释不清楚为什么是回传lb...


关于作者: 网站小编

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

热门文章