Search Insert Position 解答

Question

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

Solution 1 -- Naive

Iterate the array and compare target with ith and (i+1)th element. Time complexity O(n).

 1 public class Solution {
 2     public int searchInsert(int[] nums, int target) {
 3         if(nums==null) return 0;
 4         if(target <= nums[0]) return 0;
 5         for(int i=0; i<nums.length-1; i++){
 6             if(target > nums[i] && target <= nums[i+1]){
 7                 return i+1;
 8             }
 9         }
10         return nums.length;
11     }
12 }

Solution 2 -- Binary Search

If the target number doesn't exist in original array, then after iteration, it must be pointed by low pointer.

Time complexity O(log(n))

 1 public class Solution {
 2     public int searchInsert(int[] nums, int target) {
 3         if (nums == null || nums.length == 0)
 4             return 0;
 5         int start = 0, end = nums.length - 1, mid = (end - start) / 2 + start;
 6         while (start <= end) {
 7             mid = (end - start) / 2 + start;
 8             if (nums[mid] == target)
 9                 return mid;
10             else if (nums[mid] < target)
11                 start = mid + 1;
12             else
13                 end = mid - 1;
14         }
15         return start;
16     }
17 }
原文地址:https://www.cnblogs.com/ireneyanglan/p/4804009.html