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;
    }
    

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

  • 相关阅读:
    CSS属性值一览
    CSS属性一览
    CSS选择器一览
    HTML颜色编码
    游戏
    数据库系统概念
    关于总结
    章节测试
    我的博客皮肤
    Emeditor所有快捷键操作
  • 原文地址:https://www.cnblogs.com/duyue6002/p/7149055.html
Copyright © 2011-2022 走看看