首页 > 解决方案 > 我的 Leetcode Problem#315 的 Python 代码有什么问题

问题描述

我在 Leetcode 中解决了一个问题。它通过了 16 次中的 14 次测试。但随后出现错误。我找不到我犯错的地方。谢谢!

问题:给定一个整数数组 nums,你必须返回一个新的 counts 数组。counts 数组有一个属性,其中 counts[i] 是 nums[i] 右侧的较小元素的数量。

例子:

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

我的答案:

class Solution:
    def countSmaller(self, nums):

        new_list=[]

        for i in nums:
            count=0
            a=nums.index(i)
            my_list1=nums[a+1:]

            for x in my_list1:
                if x<i:
                    count+=1
            new_list.append(count)
        return new_list   

标签: python

解决方案


这应该为您解决它,一行理解:

[sum(1 for y in nums[i:] if y < x) for i, x in enumerate(nums)]
#[2, 1, 1, 0]

推荐阅读