您的位置:首页 > 其它

[LeetCode] Search Insert Position

2015-08-15 17:41 465 查看
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 know
target
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
.

class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int n = nums.size(), l = 0, r = n;
while (l < r) {
int mid = (l + r) / 2;
if (nums[mid] < target) l = mid + 1;
else r = mid;
}
return l;
}
};


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();
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: