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


<<:  Leetcode: 278. First Bad Version

>>:  git - 3 ( remote、git pull = git fetch + git merge )

op.27 《全领域》-全域开发实战 - 居家植物盆栽 Mvt II (C# Broker & Mysql)

op.27 纪录时空间的情话 让我们彼此之间的记忆与美好时光 永恒纪载 今天来将 Broker 进...

Day 29 如何调整 Odoo configuration 参数?

参考文章 [How to Speed up Odoo] --workers=WORKERS Spec...

Day 29. 继续来看组件基础 – Components 吧ヾ(*´∀ ˋ*)ノ

欧欧欧,竟然已经到第29天了,时间真的是咻咻咻就过了呢!明天就要结束了,真是感伤(☍﹏⁰) (解脱了...

Day30 切版笔记 - 文字排版

没想到30天这麽快就过去了 还记得决定学习前端知识的时候,带给我的都是新奇的体验,但随着学习的内容越...

[Day 06] 一个单元测试的题目-闰年的判断

过了这麽多天, 我们终於进入到主题了, 这一次我们使用的题目, 是输入一个正整数(西元年), 然後判...