題目:
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;
}
}