题目
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.
给一个排序好的数组,和一个target数据,如果找到目标,返回他的下标,如果没找到那么返回他应该插入的下标
You may assume no duplicates in the array.
你可以假设数组不重复
Example 1:
Input: [1,3,5,6], 5
Output: 2
Example 2:
Input: [1,3,5,6], 2
Output: 1
Example 3:
Input: [1,3,5,6], 7
Output: 4
Example 4:
Input: [1,3,5,6], 0
Output: 0
代码
主要运用二分的思想进行查找。
class Solution {
public int searchInsert(int[] nums, int target) {
int len = nums.length;
int i;
int start = 0,end = len-1;
if(target>nums[end])
return end+1;
else if(end<0||target<nums[start])
return start;
else if(target==nums[end])
return end;
int mid = 0;
while(start <= end )
{
mid = (start+end)>>1;
if(nums[mid] == target){
return mid;
}
else if(nums[mid]>target) {
end = mid -1;
}
else {
start = mid + 1;
}
}
return start;
}
}