[LeetCode]problem 35. Search Insert Position
来源:互联网 发布:python 字符串strip 编辑:程序博客网 时间:2024/04/28 18:20
problem 35. Search Insert Position
link
TAG
二分查找
插入
方法
能够比较快的明确思路——就是二分查找的应用。
然而写起来还是很费劲,之前那道找最长递增序列的长度其实就需要用到这道题的算法来实现快速查找插入位置(完全一样好吗!当时就写出来了啊…但是现在又忘了…)。 直接看了DISCUSS的代码.
记住了两点关键:
循环条件是
low<=high
, 其中high初始为size -1
,即没有与STL中的范围下标规范一致。(可以一致的,如果要一致,那么循环条件就是小于)循环跳出条件,必然满足
low == high+1
,所以返回low
或者high+1
都是没有问题的。但是mid的值是不确定的,在退出之前,mid值肯定是等于low的,但是退出后mid与low的关系就不一定了…(有可能是mid小1,有可能是相等)
代码
class Solution {public: int searchInsert(vector<int>& nums, int target) { int sz = nums.size() ; int low = 0 , high = sz -1 ; while( low <= high ) { int mid = low + (high - low)/2 ; int midVal = nums[mid]; if(target < midVal){ high = mid -1 ; } else if(target > midVal){ low = mid + 1 ; } else return mid ; } // here `low == high + 1` is always right return low ; }};
后记
之前一直写在Github上,最近决心找工作,得做做表面工作啊… 所以要同步起来了…orz,感觉好没意思…然而,虚荣心让我还是要这么做
0 0
- [LeetCode]problem 35. Search Insert Position
- [LeetCode]35.Search Insert Position
- LeetCode --- 35. Search Insert Position
- LeetCode 35.Search Insert Position
- [Leetcode] 35. Search Insert Position
- LeetCode 35. Search Insert Position
- [leetcode] 35.Search Insert Position
- Leetcode 35. Search Insert Position
- 35. Search Insert Position LeetCode
- [LeetCode]35. Search Insert Position
- LeetCode 35. Search Insert Position
- 【LeetCode】35. Search Insert Position
- leetcode 35. Search Insert Position
- leetcode 35. Search Insert Position
- LeetCode 35. Search Insert Position
- LeetCode *** 35. Search Insert Position
- leetcode 35. Search Insert Position
- [LeetCode]35. Search Insert Position
- NC6-数据库安装备忘
- linux用户切换命令
- PAT 1091
- SSH2.0编程 ssh协议过程实现
- 网站直达
- [LeetCode]problem 35. Search Insert Position
- Python脚本报错AttributeError: ‘module’ object has no attribute’xxx’解决方法
- C#学习笔记之ArrayList和List(1)
- 如何在Eclipse下查看JDK源代码
- 泽佑兄弟 zybros zybros.com www.zybros.com
- Winlogon通知包(Winlogon Notification Package)
- Ajax 和 JavaScript 验证用户登录
- LINUX下配置JDK与TOMCAT
- 截取字符串后三位的数字并+1