您的位置:首页 > 其它

35. Search Insert Position

2017-08-04 10:59 120 查看
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。本质是找到第一个大于等于目标值的元素的下标。
方法一:遍历数组,每个元素都和target相比较,大于target则返回元素索引,小于则指针自增1。在遍历完所有元素仍没有满足,则说明target应该放在数组的最后,同时i自增到了nums.length处,故直接返回i。时间复杂度为O(n)。

public class Solution {
public int searchInsert(int[] nums, int target) {
if(nums.length==0) return 0;
int i=0;
4000
while(i<nums.length){
if(nums[i]>=target) return i;
i++;
}
return i;
}
}


方法二:

二分查找。如果判断过程中出现了nums[mid]==target,则直接返回索引mid;如果数组中没有target这个元素,则在while循环后会出现low>high的情况,而此时low正是target所应该放的位置,故返回low。

public class Solution {
public int searchInsert(int[] nums, int target) {
if(nums.length==0) return 0;
int mid;
int low=0;
int high=nums.length-1;
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: