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

    二分法:

    #include <iostream>
    using namespace std;
    int find2(int *a,int n,int num)
    {
        int low=0,high=n-1;
        while(low<=high)
        {
            int mid=(low+high)/2;
            if(a[mid]<num)
                low=mid+1;
            else if(a[mid]>num)
                high=mid-1;
            else
                return mid;
        }
        return low;
    }
    
    int main()
    {
        int a[]={1,3,5,6};
        int num=2,n=4;
        cout<<find2(a,n,num);
    }

     another

    class Solution {
    public:
        int searchInsert(int A[], int n, int target)
        {
           return find(A, 0, n, target);
        }
        int find(int A[], int start, int end, int target)
        {
            int p = end - start;
            if(p==1 || p==0)
            {
                if(A[start] >= target) return start;
                if(A[start] < target) return start+1;
            }
            int m = p / 2;
            if(A[start + m] == target)
                return start + m;
            if(A[start + m] > target)
                return find(A, start, start+m, target);
            else
                return find(A, start+m, end, target);
        }
    };
  • 相关阅读:
    .net中Timer的使用
    计算日期的神器
    求全排列函数next_permutation
    各种排序
    求最大字段和
    炸弹时间复位
    最少步数,广搜
    数据
    水池数目
    最大岛屿
  • 原文地址:https://www.cnblogs.com/home123/p/7428717.html
Copyright © 2011-2022 走看看