zoukankan      html  css  js  c++  java
  • 35. Search Insert Position

    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

    在一个排好序的数组查找某值,存在则返回对应的value,不存在则返回能插入到数组中的index,  其实就是找到第一个大于等于目标值的下标

     1 class Solution {
     2 public:
     3     int searchInsert(vector<int>& nums, int target) {
     4         int low = 0;
     5         int high = nums.size()-1;
     6         
     7         int mid = 0;
     8         while(low <= high){
     9             mid = low + (high-low)/2;
    10             if(target <= nums[mid]){
    11                 high = mid-1;
    12             }else{
    13                 low = mid+1;
    14             }
    15         }
    16         return low;
    17     }
    18 };

    解释:

    1、条件为target<=nums[mid],意思是target小于等于中间值,则往左半区域查找。如在 {1,2,2,2,4,8,10}查找2,第一步,low=0, high=6, 得mid=3, target <= a[3],往下标{1,2,2}中继续查找。

    2、终止前一步为: low=high,得mid = low,此时如果target <= nums[mid],则high会改变,而low指向当前元素,即为满足要求的元素。如果target > nums[mid],则low会改变,而low指向mid下一个元素。

    3、如果key大于数组最后一个元素,low最后变为nums.size(),即没有元素大于key,返回 nums.size()。

  • 相关阅读:
    用element-ui搭建后台框架
    给hover加上过渡效果
    vue搭建项目
    单选框的选中事件
    Javascript开发中让代码性能变高的小技巧
    这是一个弹幕
    纯CSS打造进度条
    fixed元素随滚动条无抖动滚动
    python3实现url全编码/解码
    如何入门漏洞挖掘,以及提高自己的挖掘能力(别人写的挺好)
  • 原文地址:https://www.cnblogs.com/sankexin/p/5872616.html
Copyright © 2011-2022 走看看