zoukankan      html  css  js  c++  java
  • 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;
    }
    

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

  • 相关阅读:
    linux 11201(11203) ASM RAC 安装
    [学习笔记]多项式对数函数
    linux 10201 ASM RAC 安装+升级到10205
    tar
    [学习笔记]多项式开根
    gzip
    小朋友和二叉树
    zip
    bzoj5016 一个简单的询问
    unzip
  • 原文地址:https://www.cnblogs.com/duyue6002/p/7149055.html
Copyright © 2011-2022 走看看