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)
                   


  • 相关阅读:
    iOS:图片相关(19-05-09更)
    iOS:文字相关(19-01-08更)
    iOS:通信录(完成)(18-01-18更)
    Swift 中的Closures(闭包)详解
    Swift 中的高阶函数和函数嵌套
    Swift API设计原则
    Swift下CoreData的使用
    iOS 使用贝塞尔曲线绘制路径
    iOS CALayer使用
    iOS 多线程的使用
  • 原文地址:https://www.cnblogs.com/hrnn/p/13414007.html
Copyright © 2011-2022 走看看