zoukankan      html  css  js  c++  java
  • 【数据结构】算法 搜索插入位置 Search Insert Position

    搜索插入位置 Search Insert Position

    A sorted array of distinct integers and a target value, return the index of the array if the target is found. If not, return the index where it should be if it were inserted in order.

    in: nums = [1,3,5,6], target = 5
    out:2
    
    

    思路

    找到插入位置,小白的作法,通常都是,从头扫到尾,找到一个插入的位置,ok可以解决。

    但是作为一个大白,就不能用这种思路了。果断有效的利用有序数组的条件,进行二分查找。至于what is 二分,问度娘。

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

    Tag

    Array Binary Search

  • 相关阅读:
    MySQL多表查询
    多表关联
    MySQL数据类型 约束
    初识数据库
    socker server和 event
    os 模块 和 os模块下的path模块
    sys 模块
    time 模块
    目录规范

  • 原文地址:https://www.cnblogs.com/dreamtaker/p/15390211.html
Copyright © 2011-2022 走看看