Search Insert Position, Leetcode 解题笔记

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

还是binary search,找target或array里刚好略小于target的值的index。这种题算法很直接,关键是想好边界情况和停止循环情况。

public class Solution {
    public int searchInsert(int[] A, int target) {
        int left = 0;
        int right = A.length-1;
        while(left <= right){
            int mid = (left+right)/2;
            if(target == A[mid]) return mid;
            if(target > A[mid]){
                left = mid+1;
            }
            else{
                right = mid-1;
            }
        }
        return left;
    }
}
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