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


    1.二分查找时间复杂度O(logn)。

    二分查找的基本思想是将n个元素分成大致相等的两部分,去a[n/2]与x做比较,如果x=a[n/2],则找到x,算法中止;如果x<a[n/2],则只要在数组a的左半部分继续搜索x,如果x>a[n/2],则只要在数组a的右半部搜索x.

    时间复杂度无非就是while循环的次数!

    总共有n个元素,

    渐渐跟下去就是n,n/2,n/4,....n/2^k,其中k就是循环的次数

    由于你n/2^k取整后>=1

    即令n/2^k=1

    可得k=log2n,(是以2为底,n的对数)

    所以时间复杂度为O(logn)

    代码:

    class Solution {
    public:
        int searchInsert(int A[], int n, int target) {
            int l=0;
            int r=n-1;
            int mid;
            while (l<=r)
            {
                mid=(l+r)/2;
                if(A[mid]>target) r=mid-1;
                else if(A[mid]<target) l=mid+1;
                else return mid;
            }
            if(l==r+1)
                return l;
            else if(r=-1)
                return 0;
            else if(l=n)
                return n;
        }
    };

    2.一般方法,复杂度O(n),先找出边界,然后就是相等和两数之间的情况。

    class Solution {
    public:
        int searchInsert(int A[], int n, int target) {
            if(target>A[n-1]) return n;
            if(target<A[0]) return 0; 
            for(int i=0;i<n;++i)
            {
                if(A[i]==target) return i;
                if(i<(n-1)&&target>A[i]&&target<A[i+1])
                    return i+1;
            }
        }
    };
  • 相关阅读:
    About HDFS blocks
    Hadoop源代码分析(一)
    Hadoop源代码分析(三)
    MapReduce基础
    Pig安装与配置教程
    MapReduce数据流(三)
    MapReduce数据流(二)
    c++中的临时对象
    如何修改CMD命令行窗口下的默认路径
    VC2005: warning LNK4076: 无效的增量状态文件
  • 原文地址:https://www.cnblogs.com/fightformylife/p/4110216.html
Copyright © 2011-2022 走看看