zoukankan      html  css  js  c++  java
  • leetcode115:search -insert-position

    题目描述

    给出一个有序的数组和一个目标值,如果数组中存在该目标值,则返回该目标值的下标。如果数组中不存在该目标值,则返回如果将该目标值插入这个数组应该插入的位置的下标
    假设数组中没有重复项。
    下面给出几个样例:
    [1,3,5,6], 5 → 2
    [1,3,5,6], 2 → 1
    [1,3,5,6], 7 → 4
    [1,3,5,6], 0 → 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

    示例1

    输入

    复制
    [1,3,5,6],5

    输出

    复制
    2
    class Solution {
    public:
        /**
         *
         * @param A int整型一维数组
         * @param n int A数组长度
         * @param target int整型
         * @return int整型
         */
        int searchInsert(int* A, int n, int target) {
            // write code here
            if (n==0) return 0;
            int l=0,h=n,m;
            while (l<h){
                m=l+((h-l)>>1);
                if (A[m] >target){
                    h=m;
                }
                else if (A[m]<target){
                    l=m+1;
                }
                else {
                    return m;
                }
                
            }
            if (target<A[0])return 0;
            if (target>A[n-1]) return n;
            return h;
        }
    };
    #
    #
    # @param A int整型一维数组
    # @param target int整型
    # @return int整型
    #
    class Solution:
        def searchInsert(self , A , target ):
            # write code here
            if not A:
                return 0
            if target in A:
                return A.index(target)
            else :
                for i in range(len(A)):
                    if A[i]>target:
                        return i
                return len(A)
                   


  • 相关阅读:
    hdu-1698(线段树,区间修改)
    hdu-1394(线段树)
    hdu-1166(线段树)
    hdu-1251(string+map)
    hdu-1711(kmp算法)
    hdu-2191(完全背包+二进制优化模板)
    hdu-2844(完全背包+二进制优化模板)
    hdu-1171(多重背包+二进制优化)
    SpringMVC 参数中接收数组、List写法
    如何高效的查询数组中是否包含某个值
  • 原文地址:https://www.cnblogs.com/hrnn/p/13414007.html
Copyright © 2011-2022 走看看