leetcode题目之求数值下标问题

这道题意思是给出一个有序的列表,里面的元素类型都是整型,然后给定一个数字,如果这个数字在这个列表中出现了,那就返回这个数字在这个列表中的下标(从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.

Example 1:

Input: [1,3,5,6], 5
Output: 2

Example 2:

Input: [1,3,5,6], 2
Output: 1

Example 3:

Input: [1,3,5,6], 7
Output: 4

Example 4:

Input: [1,3,5,6], 0
Output: 0

我的想法是:首先如果这个数组为空,那就是输出第一个下标0了,如果不为空,那就遍历数组,如果找到大于等于这个数字的某个元素,那就输出此时的下标,这里要分类讨论:

1、找到等于这个数值的元素了,肯定就返回这个数值的下标

2、找到大于这个数值的元素,说明此时这个数值前面的值比要比较的值小,但是当前的数值比要比较的数字大,那么就意味着要把比较的target值插入到当前下标这儿合适,比如例子[1,3,5,6],此时target是4,那么遍历到元素5的时候发现比4大,说明5前面的3比4小,5比4大,此时插入4应该是在3的后面,也就是当前5的下标了

如果整个数组的值都小于目标数字target怎么办?那就插入到数组尾了。因此直接返回len(nums)-1

具体代码如下:

class Solution:
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        if len(nums) == 0:
            return 0

        for i in range(len(nums)):
            if nums[i] == target:
                return i
            elif nums[i]>target:
                return i
            if i == len(nums)-1:
                return len(nums)


if __name__ == '__main__':
    S = Solution()
    obj = list(input('').split(','))
    obj = list(map(int, obj))
    print(obj)
    n = int(input(''))
    print(S.searchInsert(obj,n))

运行结果如图:

谢谢观看!

2018.12.13 3:38 am

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值