Question:
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 len=nums.length;
int result=14;
for(int i=0;i<=len-1;i++)
{
if(i==0&&nums[i]>target)
{
result=0;
break;
}
if(nums[i]==target)
{
result=i;
break;
}
if((i<=len-2&&nums[i]<target&&nums[i+1]>target)||(i==len-1&&nums[i]<target))
{
result=i+1;
break;
}
}
return result;
}
}
然后用二分。。。不太懂为什么复杂度还是这么慢。。。
public int searchInsert(int[] nums, int target) {
int low=0;
int len=nums.length;
int high=len-1;
int result=0;
if(target<nums[0])
return 0;
if(target>nums[len-1])
return len;
while(low<=high)
{
int mid = (high - low) / 2 + low;
if(target<nums[mid])
high=mid-1;
else if(target>nums[mid])
low=mid+1;
else
return mid;
}
return low;
}