题目:
思路:
这题和前几题类似,我就想用双指针,然后设置了个外层双指针,和内层双指针,最后发现,内层双指针还好,外层双指针无法判断缩放方向,不知道左缩还是右缩放,测试里面发现了,但是解决不了qaq,最终还是没有做出来(理论上我感觉如果能判断外层缩放方向,时间复杂度低一点)
代码:
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
length = len(nums)
nums.sort()
num_first = 0
num_last = length-1
templist =[]
res = []
flag = 1
while num_last>=(num_first+3):
max_fournum = nums[num_first]+nums[num_last]+nums[num_last-1]+nums[num_last-2]
min_fornum = nums[num_first]+nums[num_first+1]+nums[num_first+2]+nums[num_last]
if target<=max_fournum and target>=min_fornum:
left_point = num_first+1
right_point = num_last-1
while left_point<right_point:
sum_fournum = nums[num_first]+nums[left_point]+nums[right_point]+nums[num_last]
if sum_fournum>target:
right_point -=1
elif sum_fournum<target:
left_point +=1
else:
templist.extend([nums[num_first],nums[left_point],nums[right_point],nums[num_last]])
if templist not in res:
res.append(templist[::])
templist.clear()
right_point -=1
left_point +=1
if abs(target-max_fournum)>abs(target-min_fornum):
num_last -=1
elif abs(target-max_fournum)<abs(target-min_fornum):
num_first +=1
else:
if flag == 1:
num_first += 1
flag +=1
if flag ==2:
num_first -=1
num_last -=1
flag = 1
elif target>max_fournum:
num_first +=1
elif target<min_fornum:
num_last -=1
else:
pass
return res