zoukankan      html  css  js  c++  java
  • Search Insert Position 分类: Leetcode 2014-12-06 16:18 78人阅读 评论(0) 收藏

    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

    最初的想法是从头到尾遍历这个数组,这样也是可以做的

    class Solution {
    public:
        int searchInsert(int A[], int n, int target) {
            if(target<=A[0]) return 0;
            if(target==A[n-1]) return n-1;
            if(target>A[n-1]) return n;
            int begin=0,last=n-1;
            while(A[begin]<target)
            {
                    begin++;
            }
            return begin;
        }
    };
    不过用二分法在某些情况的确可以提高查找效率

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


    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    Functors in OpenCV
    绘图及注释
    矩阵操作
    图像与大数组类型
    OpenCV的数据类型
    OpenCV入门
    去掉微信公众号里面的菜单栏
    解决python语言在cmd下中文乱码的问题
    解决python无法安装mysql数据库问题
    微信分享功能出现签名错误功能导致的原因
  • 原文地址:https://www.cnblogs.com/learnordie/p/4656985.html
Copyright © 2011-2022 走看看