您的位置:首页 > 其它

[leetcode]Search Insert Position

2016-01-19 17:37 260 查看
题目描述如下:

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

虽然是medium难度的题目,但其实就是一个二分搜索+最后的位置判断,实际上并不难,通过率不高可能是对位置判断有误。

代码如下:

public class Solution {
public int searchInsert(int[] nums, int target) {
int res = 0;
if(nums.length == 0) return res;
boolean isFind = false;
int first = 0, last = nums.length - 1, mid;
while(first < last){
mid = (first + last) / 2;
if(nums[mid] == target){
res = mid;
isFind = true;
break;
}else if(nums[mid] < target){
first = mid + 1;
}else{
last = mid;
}
}
if(!isFind){
if(last == nums.length - 1) {
if(target > nums[nums.length - 1])
res = nums.length;
else res = nums.length - 1 > 0 ? nums.length - 1 : 0;
}else if(last == 0){
if(target > nums[0])
res = 1;
else res = 0;
}else{
if(target > nums[last])
res = last + 1;
else res = last;
}
}
return res;
}
}


题目链接:https://leetcode.com/problems/search-insert-position/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: