您的位置:首页 > 编程语言 > Java开发

【leetcode】【35】Search Insert Position

2015-11-06 19:43 417 查看

一、问题描述


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.
[1,3,5,6]
, 5 → 2
[1,3,5,6]
, 2 → 1
[1,3,5,6]
, 7 → 4
[1,3,5,6]
, 0 → 0

二、问题分析

根据题目描述发现数组是有序的,而我们要进行的操作是一次查找,显然该采用二分查找法,至于查找的结果无非有两种,第一存在,直接返回index即可,第二不存在,那么low==high的位置即为所插之位。


三、Java AC 代码

</pre><pre name="code" class="java">public int searchInsert(int[] nums, int target) {
int high = nums.length-1;
int low = 0;
int mid = 0;
while(low<=high){
mid = (low+high)/2;
if (nums[mid]==target) {
return mid;
}else if (nums[mid]<target) {
low = mid + 1;
}else {
high = mid - 1;
}
}
return low;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息