题目:
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.
思路与步骤:
其实就是一个查找问题。
这里写出了顺序查找,学习并实现了折半查找。其他查找方法待以后学习了查找算法再继续。
编程实现:
顺序查找:
public class Solution {
public int searchInsert(int[] nums, int target) {
// SequentialSearch
int i = 0;
while(i<nums.length && target>nums[i]) i++;
return i;
}
折半查找:
public class Solution {
public int searchInsert(int[] nums, int target) {
// BinarySearch
if(nums.length==1) return target > nums[0] ? 1 : 0;
int begin = 0, end = nums.length-1, mid = (begin+end)/2;
while(begin <= end){
mid = (begin+end)/2;
if(target == nums[mid]) return mid;
else if(target < nums[mid]) end = mid-1;
else if(target > nums[mid]) begin = mid+1;
}
if(target < nums[mid]) return mid;
else return mid+1;
}
}