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
給定一個排序數組,和一個指定的值,若是找到這個值,返回這個值位置,若是沒有找到,返回這個值在數組中的插入位置。
假設數組中沒有重複的元素。數組
1、最直接的查找算法,從左向右搜索。
2、使用二分查找算法。spa
算法實現類(直接查找).net
public class Solution { public int searchInsert(int[] A, int target) { if (A == null) { return -1; } int i; for (i = 0; i < A.length; i++) { if (A[i] >= target) { return i; } } return i; } }
算法實現類(二分查找)code
public class Solution { public int searchInsert(int[] A, int target) { int mid; int lo = 0; int hi = A.length - 1; while (lo <= hi) { mid = lo + (hi - lo)/ 2; if (A[mid] == target) { return mid; } else if (A[mid] < target){ lo = mid + 1; } else { hi = mid - 1; } } return lo; } }