LeetCode & Q35-Search Insert Position-Easy

Array Binary Search

Description:

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

my Solution:

public class Solution {
    public int searchInsert(int[] nums, int target) {
        int i = 0;
        for(i = 0; i < nums.length; i++) {
            if(target <= nums[i])
                break;
        }
        if(i < nums.length)
            return i;
        else
            return i++;
    }
}

Best Solution:

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

差别就在于,我用的是从首到尾循环,没有完全利用好已排序这个条件。最优解用的是二分法,基本是排序里的算法。

posted @ 2017-07-11 09:46  6002  阅读(175)  评论(0编辑  收藏  举报