==============================================================================
【id】#18
【title】4Sum
【description】
Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
The solution set must not contain duplicate quadruplets.
Example:
Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.
A solution set is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
【idea】
类似于3sum,首先排序得到有序数组(从小到大)。然后找到两个固定数,利用两个指针遍历剩下的元素,得到最后的结果。
先找第一个固定数字位置为i,如果这个数字大于 target/4.0,说明不会符合结果了;为了保证结果中没有重复,要做一个去重判断。如果找到的这个固定数字与上次的相同直接跳过。
找第二个固定数字,位置为j(在i后),原理同第一个,也要做去重判断。
然后用两个双指针进行后边数字的判断。初始化low为j+1,high为length-1,也就是剩下数组的首尾。如果i,j,low,high四个位置的数字加和小于target,low+1;如果大于target,high-1,如果相等,加入结果list中。
【code】
class Solution(object):
def fourSum(self, nums, target):
res = []
nums = sorted(nums,reverse = False)
for i in range(len(nums)):
if nums[i] > target/4.0: break
if i>0 and nums[i] == nums[i-1]: continue
for j in range(i+1, len(nums)):
if nums[j] > (target - nums[i])/3.0: break
if j > i+1 and nums[j] == nums[j-1]: continue
low = j+1
high = len(nums) - 1
while low < high:
tmp = nums[i] + nums[j] + nums[low] + nums[high]
if tmp == target :
res.append([nums[i], nums[j], nums[low], nums[high]])
while (low < high and nums[low] == nums[low+1]): low += 1
while (low < high and nums[high] == nums[high-1]): high -= 1
low += 1
high -= 1
elif tmp > target:
high -= 1
else:
low += 1
return res