python - 我的 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
解决方案
这应该为您解决它,一行理解:
[sum(1 for y in nums[i:] if y < x) for i, x in enumerate(nums)]
#[2, 1, 1, 0]
推荐阅读
- django - 有没有办法在 django 表单中动态过滤查询集以获得正确的外键?
- syntax-error - 为什么这个简单的 LISP 函数会抛出错误?
- javascript - 如何在 jQuery timepicker 插件中设置最大时间限制
- java - 获取 URL 参数并在 HTML 页面中打印
- python - QFileDialog 总是在主窗口后面打开
- python-3.x - 如何迭代由元组列表组成的字典?
- module - Joomla 3.9.13 中的随机图像模块有问题吗?
- php - 关于设计课程系统。我应该何时检查到期或未到期的作业?我应该把这个逻辑放在哪里?
- angular - primeNG 表上的可编辑行问题
- reactjs - reactjs中formik表单初始值如何设置前置字段数据