Python 4LEETCODE中的SUM可运行但未能提交
我目前正在研究leetcode 4sum问题 给定一个由n个整数组成的数组num和一个整数目标,num中是否有元素a、b、c和d,使得a+b+c+d=target?在数组中找到所有唯一的四元组,该数组给出目标的和。 注: 解决方案集不得包含重复的四个组 我能够运行结果,结果被接受。但是,当我尝试提交它时,会出现以下错误消息Python 4LEETCODE中的SUM可运行但未能提交,python,Python,我目前正在研究leetcode 4sum问题 给定一个由n个整数组成的数组num和一个整数目标,num中是否有元素a、b、c和d,使得a+b+c+d=target?在数组中找到所有唯一的四元组,该数组给出目标的和。 注: 解决方案集不得包含重复的四个组 我能够运行结果,结果被接受。但是,当我尝试提交它时,会出现以下错误消息 KeyError: 0 for combination_n in a2[n]: Line 24 in fourSum (Solution.py) ret = Sol
KeyError: 0
for combination_n in a2[n]:
Line 24 in fourSum (Solution.py)
ret = Solution().fourSum(param_1, param_2)
Line 61 in _driver (Solution.py)
_driver()
Line 72 in <module> (Solution.py)
我可以知道发生了什么事吗,非常感谢 - 你的字典里有一个关于边缘情况的错误,我还没弄明白。对于范围(1,len(nums)-i)内的j,最有可能的错误就在这一行附近
:
- 一旦你解决了这个问题,你很可能会得到一个TLE,因为你的解决方案是N^4的顺序
- 这将过去:
类解决方案:
def fourSum(自身、nums、目标):
def查找和(lo、hi、target、n、out、res):
如果hi-lo+1nums[hi]*n:
返回
如果n==2:
当lolo和nums[i-1]!=nums[i]):
求和(i+1,hi,target-nums[i],n-1,out+[nums[i]],res)
nums.sort()
res=[]
求和(0,len(nums)-1,target,4,[],res)
返回res
a2在这种情况下没有0键。对不起,您想怎么办mean@VicentLHKROT,您的字典a2
不包含键0
,因此a2[0]
会抛出一个
import collections
class Solution:
def fourSum (self, nums, target):
#all possible combination of any two numbers in the list
a2={}
# append all combination to a particular value
# format{value:rank in list, rank in list}
for i in range(len(nums)):
for j in range(1,len(nums)-i):
if nums[i]+nums[j+i] not in a2:
a2[nums[i]+nums[j+i]]=[[i,j+i]]
elif [j+i,i] not in a2[nums[i] + nums[j+i]]:
a2[nums[i] + nums[j+i]].append([i,j+i])
final_list=[]
#iterate all possible value of any two items in the list "nums"
#find all the combination of value to achieve the target
for sumofa2 in a2:
n=target-sumofa2
# find the cooresponding rank in list to achieve the value
for combination_n in a2[n]:
for combination_sumofa2 in a2[sumofa2]:
list = combination_n + combination_sumofa2
if len(set(list)) == len(list):
#replace the actual value to the coresponding rank in the list
for n,rank in enumerate(list):
list[n]=nums[rank]
list.sort()
#avoid duplication in the list
if list not in final_list:
final_list.append(list)
return (final_list)
print(final_list)
class Solution:
def fourSum(self, nums, target):
def find_n_sum(lo, hi, target, n, out, res):
if hi - lo + 1 < n or n < 2 or target < nums[lo] * n or target > nums[hi] * n:
return
if n == 2:
while lo < hi:
summation = nums[lo] + nums[hi]
if summation == target:
res.append(out + [nums[lo], nums[hi]])
lo += 1
while lo < hi and nums[lo] == nums[lo - 1]:
lo += 1
elif summation < target:
lo += 1
else:
hi -= 1
else:
for i in range(lo, hi + 1):
if i == lo or (i > lo and nums[i - 1] != nums[i]):
find_n_sum(i + 1, hi, target - nums[i], n - 1, out + [nums[i]], res)
nums.sort()
res = []
find_n_sum(0, len(nums) - 1, target, 4, [], res)
return res