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();
        }
    };
  • 相关阅读:
    (转)Ubuntu init启动流程分析
    读懂diff
    vs2010 sp1
    Git .gitignore文件的使用
    第一次尝试节奏跑(乳酸门槛跑)
    放松跑、间歇跑、节奏跑和LSD
    Tomcat6配置webdav协议
    Content-disposition
    php5.3到php7.0.x新特性介绍
    随机生成字符串
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4732835.html
Copyright © 2011-2022 走看看