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

    最常见的思路:顺序查找,顺序找到第一个大于等于带插入数据的元素的位置,时间复杂度O(N),注意到题目中原数组是有序的,且是查找问题,自然想到二分查找。

    二分查找的代码如下:

    int BinaryResearch(int A[],int low,int high,int target)
    {
        int l = low;
        int h = high;
        while(l<=h)
        {
           int mid = (int)((h+l)/2);
           if(A[mid]==target) return mid;
           else if(A[mid]<target) l = mid+1;
           else h = mid-1;
        }
        return -1;
    }

    二分查找运用到此题目中时,若待插入数据在原数组中可以查找到(原数组中有与待插入数据相同的数),则插入到这个位置即可,对应到上述代码中查找成功return mid;即可;

    关键在于插入数据在不在原数组中的时候,怎么考虑呢?在二分查找中,如果查找失败,则一定是low>high的情况。例如在数组[1,2,3,4,5,6,8,9]中查找7,那么返回时,其low指针指向8的位置,而high指针指向6的位置,即low指向第一个大于查找目标的数,high指向比7小的最大的数,显然low的位置便是插入位置。

    时间复杂度为O(logN)。

    代码:

    int searchInsert(int A[], int n, int target) {
        int low = 0;
        int hig = n-1;
        while(low<=hig)
        {
            int mid = (int)((low+hig)/2);
            if(A[mid]==target) return mid;
            else if(A[mid]<target) low = mid+1;
            else hig = mid-1;
        }
        return low;
        }


  • 相关阅读:
    SpringMVC-数据处理(三)
    SpringMVC-Controller配置详解(二)
    SpringMVC-简介和执行原理分析(一)
    0913_Python初识及变量
    WebStorm快捷键操作
    纯CSS气泡框实现方法探究
    前端的一些常用DOM和事件归纳
    JS原型与原型链终极详解
    设计趋势:网页设计中的幽灵按钮
    首页焦点图myFocus插件
  • 原文地址:https://www.cnblogs.com/sunp823/p/5601441.html
Copyright © 2011-2022 走看看