欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  Java

LeetCode & Q35-Search Insert Position-Easy

程序员文章站 2022-04-09 11:21:52
...
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;
}

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

以上就是LeetCode &amp; Q35-Search Insert Position-Easy的详细内容,更多请关注其它相关文章!