iT邦幫忙

0

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...


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
阿瑜
iT邦研究生 4 級 ‧ 2022-01-07 16:42:04

好扯! 大神是你吧
好久沒寫LC

我要留言

立即登入留言