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)
                   


  • 相关阅读:
    TIME_WAIT和CLOSE_WAIT的区别
    shell备份脚本
    No package 'eventlog' found
    Linux下升级安装Python-3.6.2版本
    mysql的binlog安全删除的一种方法
    windows 清理 cbs.log 文件
    Linux crontab 查看所有用户的crontab任务
    java抽象类与接口回顾
    java类的回顾
    windows的MySQL安装
  • 原文地址:https://www.cnblogs.com/hrnn/p/13414007.html
Copyright © 2011-2022 走看看