35. Search Insert Position

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

思路: 由于给定的一维数组是有序的,先判断头元素跟尾元素跟target的大小,
target array[length -1],返回length. 都不满足则二分查找

public class Solution {
    public int searchInsert(int[] nums, int target) {
        if (nums == null || nums.length == 0) return -1;

        if (nums[0] > target) return 0;
        else if (nums[nums.length - 1] < target) return nums.length; 
        else {
            int start = 0;
            int end = nums.length - 1;
            int index = -1;
            while(start + 1 < end) {
                int mid = start + (end - start) / 2;
                if (nums[mid] == target) {
                    return mid;
                } else if(nums[mid] > target) {
                    end = mid;
                } else {
                    start = mid;
                }
            }

            if (nums[start] < target && nums[end] >= target) {
                return end;
            }
            return start;

        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s