题目描述: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.
中文理解:给出一个排序的数组和一个指定的值,数组没有重复元素,如果该值在数组中,则返回该值的下标,如果该值不存在数组中,则返回该值在数组中应该插入的下标。
解题思路:由于数组是排序的,解法一,直接一遍遍历数组,若找到某一个值与该值相等返回这个下标,如果遇到第一个大于该值的值,返回该值的下标;解法二,典型的折半查找,设置start,mid,end来每次进行折半筛选,最后返回start的值即为结果。
代码(java):
class Solution {
public int searchInsert(int[] nums, int target) {
int start=0;
int end=nums.length-1;
int mid=(start+end)/2;
while(start<=end){
if(target<nums[mid]){
end=mid-1;
}
else if(target>nums[mid]){
start=mid+1;
}
else if(target==nums[mid]){
return mid;
}
mid=(start+end)/2;
}
return start;
}
}