35. Search Insert Position 查找插入位置
来源:互联网 发布:php登陆后显示用户名 编辑:程序博客网 时间:2024/05/08 08:22
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Example 1:
Input: [1,3,5,6], 5Output: 2
Example 2:
Input: [1,3,5,6], 2Output: 1
Example 3:
Input: [1,3,5,6], 7Output: 4
Example 1:
Input: [1,3,5,6], 0Output: 0
class Solution { public int searchInsert(int[] nums, int target) { int left=0; int right=nums.length-1; while(left<=right){ int mid=(right-left)/2+left; if(nums[mid]<target){ left=mid+1; }else if(nums[mid]>target){ right=mid-1; }else{ return mid; } } return left; }}
解题思路:
相当于快排二分法,每次跟数组里面的middle位置的值进行比较,知道left等于right为止,也就是只剩下一个数值。
为了防止right和left是数值很大的值,(left+right)/2可能会造成overflow,所以采用(right-left)/2+left来表示mid位置。
关于最后return left是因为循环的部分是只要left<=right,只要没有比较出结果,就一直二分法进行下去,所以如果没有跟数组里面的某个值相等的话,最后return的left值就是应该插入的位置
阅读全文
0 0
- 35. Search Insert Position 查找插入位置
- LeetCode Search Insert Position查找插入位置
- Search Insert Position 查找插入的位置
- LeetCode---35. Search Insert Position(查找插入位置)
- leetcode 35. Search Insert Position搜索插入位置(二分查找)
- Search Insert Position 插入位置
- 【LeetCode】- Search Insert Position(查找插入的位置)
- LeetCode | Search Insert Position(查找插入位置)
- LeetCode OJ 之 Search Insert Position (查找插入位置)
- Leetcode刷题记—— 35. Search Insert Position(查找插入位置)
- Leetcode #35. Search Insert Position 搜寻插入位置 解题报告
- Search Insert Position 寻找插入的位置
- 【LintCode】Search Insert Position 搜索插入位置
- 搜索插入位置:Search Insert Position
- Search Insert Position 找适合插入的位置@LeetCode
- 寻找序列的插入位置 Search Insert Position
- [Leetcode] Search Insert Position 寻找插入的位置
- 60.Search Insert Position-搜索插入位置(容易题)
- iOS 应用性能提高 -- UI
- osg获取纹理节点纹理方法
- BootStrap入门(一)
- 工作日志:Timer.schedule()的理解
- Matlab 关于彩色图像的平移、旋转以及对称处理
- 35. Search Insert Position 查找插入位置
- 小白每天学习两个函数D5-(fseek,ftell)
- 利用Kibana图表化Elasticsearch中的数据
- Ubuntu16.04禁用ipv6
- psql: could not connect to server: No such file or directory&&PGHOST
- 算法训练 字符串变换
- CEF3之js与c++交互问题解决资料
- PhantomJS初识
- Android Studio Opengl Cmake 配置 编译 jni c++ 调用opengl