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;
        }
    };


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

  • 相关阅读:
    信息探测
    Hdu 1262 寻找素数对
    Hdu 1263 水果
    Hdu 1261字串数
    Hdu 1253 胜利大逃亡
    Hdu 1237简单计算器
    Hdu 1235 统计同成绩学生人数
    Hdu 1236 排名
    Hdu 1233 还是畅通工程
    Hdu 1234 开门人和关门人
  • 原文地址:https://www.cnblogs.com/learnordie/p/4656985.html
Copyright © 2011-2022 走看看