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

 

Solution 1 (suggested): binarCodearch

public class Solution {
    public int searchInsert(int[] nums, int target) {
        //binary search 
        int low = 0, high = nums.length-1; 
        while ( low <= high) {
            int mid = low + (high - low)/2; 
            if (nums[mid] == target) return mid; 
            else if (nums[mid] > target) high = mid-1; 
            else low = mid + 1; 
        }
        return low; 
    }
}

Solution 2: check one by one

public class Solution {
    public int searchInsert(int[] nums, int target) {
        boolean previous = false, next = false; 
        int i = 0;
        if (target < nums[i]) return i; 
        if (nums.length == 1) return target <= nums[0]? 0:1;
        for ( i = 0; i < nums.length-1; i++) {
            if (nums[i] == target) return i; 
            if (nums[i] < target) previous = true; 
            if (nums[i+1] > target) next = true;
            if (previous && next) return (i+1); 
            previous = false; 
            next = false; 
        }
        return target == nums[i] ? i:(i+1); 
    }
}
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