我无法使用Python在leetcode中传递3sum问题的时间限制测试。有没有人能够做到这一点?谢谢!
我现有的代码:
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
solution=[]
for i in range(len(nums)):
tmp={}
for j in range(1+i,len(nums)):
if -(nums[j]+nums[i]) in tmp:
solution.append(tuple(sorted((nums[j],nums[i],-(nums[j]+nums[i])))))
else:
tmp[nums[j]]=j
return list(set(solution))
答案 0 :(得分:0)
不知道你的解决方案有什么问题。我认为诀窍是将结果对象视为multisets,在python中称为collections.Counter
。我们还可以使用itertools.combinations
来完成从输入中获取3的所有组合。
import itertools
import collections
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
for t in itertools.combinations(nums, 3):
if sum(t) == 0:
c = collections.Counter(t)
if c not in res:
res.append(c)
return [list(t.elements()) for t in res]
测试:
Solution().threeSum([-1, 0, 1, 2, -1, -4])
# --> [[-1, 0, 1], [-1, -1, 2]]
答案 1 :(得分:0)
{{1}}
答案 2 :(得分:-1)
可能不是有效的,但它很简单。
var age=prompt("What is your age=");
function check(age){
if (Number(age)===18){
console.log("Cong its your first ride");
}
else if(Number(age)>18){
console.log("Powering On");
}
else{
console.log("Not qualify for ride");
}
}
check(age);
很高兴有帮助! 评论是否有任何疑问。