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
我的思路:
有序数组
首先考虑特殊情况,如果数组为空,那么输出的结果就一定为0;
当数组不为空时,对数组中的每个元素依次遍历,
当nums[i]等于target时,直接输出i,这便是target的索引;
当nums[i]小于target时,表示target可能还在后面,所以i增加1;直到i等于nums数组的长度,停止遍历,返回数组长度,及target应插入的位置。
当nums[i]大于target时,表示target不在数组中,同时target应该插入的位置为nums[i]前面的位置,因为前面遍历的nums[i-1]及前面的数都是小于target的,而此时的nums[i]又大于target。所以不再需要继续往后遍历,直接返回索引i,target应插入的位置。
class Solution {
public int searchInsert(int[] nums, int target) {
if(nums.length == 0){
return 0;
}
int i;
for(i = 0;i<nums.length;i++){
if(nums[i]==target){
return i;
}
else if(nums[i]>target){
return i;
}
}
return i;
}
}
leetcode上的solution:
leetcode上有个solution给出了二分法的解决办法。
首先两个记录边界的指针,low,和high(nums.length-1),还有中间值的指针,mid=(low+high)/2
class Solution {
public int searchInsert(int[] nums, int target) {
int low = 0;int high = nums.length-1;
for(low<high){
int mid = (low + high)/2;
if(nums[mid] == traget) return mid;
else if(nums[mid]>target){
high = mid-1;
}
else low = mid+1;
}
//return mid;
return low;
}
}