[LeetCode] Search Insert Position
2015-08-15 17:41
465 查看
The basic idea is to use binary search: keep two pointers
The code is as follows. Note that we initialize
In fact, this is just the sub-routine
Well, the system
land
rfor the current search range, then find the middle element
nums[mid]in this range. If
nums[mid] < target, we know
targetshould 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 = ninstead of
n - 1, which easily handles the case that
targetneeds 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
searchin Solution 2 of Stefan's post. Thank Stefan for posting such a nice article!
Well, the system
lower_boundmay 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(); } };
相关文章推荐
- **ios提交应用加急审批**
- Openerp工作流参考资料
- HDU 5297(Y sequence-Mobius函数容斥+迭代)
- C以及Objective-C测试题讲解(上)
- PHP 实现获取服务器端IP地址
- java学习个人笔记---容器之Map与Set关系
- MySql视图
- MBProgressHUD的使用
- 数组速度比较
- [LeetCode] 032. Longest Valid Parentheses (Hard) (C++)
- Win7(32/64)VS2010配置编译GDAL环境(图文教程+亲测可用!)
- JSON数据解析
- Ubuntu日常配置-优雅的界面Numix
- POJ 1152 An Easy Problem!(进位制)
- Leetcode#45||Jump Game II
- IOS OC 多态(白话)
- Django基础学习<2>
- onmousedown和onmouseup事件
- 机房收费系统(二)——组合查询
- 131. Palindrome Partitioning