LeetCode OJ 35. Search Insert Position
2016-05-23 23:36
381 查看
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.
Here are few examples.
【题目分析】
给定一个已排序的数组,数组中没有重复的数字。给定一个数字找到该数子出现的位置,如果数组中不存在该数字,则返回如果插入该数字应该插入的位置。
【思路】
涉及到已排序的数组,我们一般都会采用二分查找算法。如果目标数字存在,则直接返回结果即可。若不存在呢?
研究一下二分查找,left和right相等时,如果此时的值和目标值相同则left就是应该返回的结果,否则的话我们比较一下目标值和下标left对应的值的大小。如果目标值较大,则返回left+1,否则返回left。
【java代码】
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
【题目分析】
给定一个已排序的数组,数组中没有重复的数字。给定一个数字找到该数子出现的位置,如果数组中不存在该数字,则返回如果插入该数字应该插入的位置。
【思路】
涉及到已排序的数组,我们一般都会采用二分查找算法。如果目标数字存在,则直接返回结果即可。若不存在呢?
研究一下二分查找,left和right相等时,如果此时的值和目标值相同则left就是应该返回的结果,否则的话我们比较一下目标值和下标left对应的值的大小。如果目标值较大,则返回left+1,否则返回left。
【java代码】
public class Solution { public int searchInsert(int[] nums, int target) { if(nums.length == 0 || nums == null) return 0; int left = 0; int right = nums.length - 1; while(left <= right){ if(left == right){ if(nums[left] == target) return left; else break; } int mid = (right - left)/2 + left; if(nums[mid] > target) right = mid - 1; else if(nums[mid] < target) left = mid + 1; else return mid; } if(nums[left] < target) return left+1; else return left; } }
相关文章推荐
- Webcast / 技术小视频制作方法——自己动手录制video轻松搞定
- C#中调用Matlab人工神经网络算法实现手写数字识别
- HDU 5692 Snacks (DFS序 + 线段树区间更新 好题)
- Java通过JDBC连接Mysql数据库的方法和实例【图文说明】
- [设计模式]之三:单例模式
- 一个毕业5年的IT男的感悟
- ruby注意点
- Java高并发响应力
- hudson集成maven构建、多环境打包发版
- ASP.NET第一个项目,希望我遇到的一些问题对各位会有所帮助
- 随机数的产生
- 设计模式学习--迭代器模式
- 创建和使用一个新的系统调用
- 如何在C++中播放音频(几行代码搞定)
- xcode 统计代码行数
- C++11中的线程支持库(Thread support library)
- Day3作业:ha_proxy配置文件修改
- Zookeeper 安装和配置
- 四元数和旋转轴及旋转角度之间的转换理解实例
- python 练习 1