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)
                   


  • 相关阅读:
    Android高级控件(四)——VideoView 实现引导页播放视频欢迎效果,超级简单却十分的炫酷
    Android源代码文件夹结构说明
    IOS-Storyboard控制器切换之TabBar(3)
    若干排序算法简单汇总(一)
    Linux地址ping不通情况怎么办?
    pve三种操作方式
    Office Add-in 设计规范与最佳实践
    编辑您的代码
    持续集成
    人工智能到底能给我们带来什么?
  • 原文地址:https://www.cnblogs.com/hrnn/p/13414007.html
Copyright © 2011-2022 走看看