zoukankan      html  css  js  c++  java
  • [LeetCode] Search Insert Position

    The basic idea is to use binary search: keep two pointers l and r for the current search range, then find the middle element nums[mid] in this range. If nums[mid] < target, we knowtarget should at least be inserted after nums[mid], so we update l = mid + 1. Otherwise, update r = mid.

    The code is as follows. Note that we initialize r = n instead of n - 1, which easily handles the case that target needs to be inserted after all the elements of nums.

     1 class Solution {
     2 public:
     3     int searchInsert(vector<int>& nums, int target) {
     4         int n = nums.size(), l = 0, r = n;
     5         while (l < r) {
     6             int mid = (l + r) / 2;
     7             if (nums[mid] < target) l = mid + 1;
     8             else r = mid;
     9         }
    10         return l;
    11     }
    12 };

    In fact, this is just the sub-routine search in Solution 2 of Stefan's post. Thank Stefan for posting such a nice article!

    Well, the system lower_bound may also be used, which just takes 1 line :-)

    class Solution { 
    public:
        int searchInsert(vector<int>& nums, int target) {
            return lower_bound(nums.begin(), nums.end(), target) - nums.begin();
        }
    };
  • 相关阅读:
    京东精益敏捷教练分享:敏捷助力产品创新!
    设计规范 | 详解组件控件结构体系
    Axure响应式进阶
    通讯录表设计
    TEST1
    c#练习四单元总结
    窗体控件应用总结(1)
    .NET(c#理解)
    test2-11
    test1-1
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4732835.html
Copyright © 2011-2022 走看看