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)
                   


  • 相关阅读:
    python D5
    python D4
    python D3
    python D2
    python D1
    day12——闭包,装饰器,迭代器
    day11——考试python2和python3的区别
    day10——动态参数,名称空间,global,nonlocal
    day9——函数初识
    day8——文件操作
  • 原文地址:https://www.cnblogs.com/hrnn/p/13414007.html
Copyright © 2011-2022 走看看