https://leetcode.com/problems/4sum/description/
For example, given array S = [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] ]
思想: 找出两个数的和为一个目标值:暴力两个for,时间复杂度为O(n^2)。
故简单的o(n)的方法:
首先对数组进行排序
通过从两头向中间找,若两数之和大于目标值,则左指针不变,右指针左移。。。
那m找三个数的和为一个target,通过一个for循环固定一个值,剩下的就化简为2sums
那m找四个数的,用两个for固定两个值,。。其实一共要四个指针
注意点:每个指针只要进行移动,都要考虑去重,即j指针每次固定的数不能相同,保证找出的结果不会重复
指针进行移动时不要越界
通过python 用以上方法还是超时,做的改进是,固定第一个值a后先判断 a>target/4.0 ,直接break
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
nums.sort()
result = []
len_nums = len(nums)
i = 0
while i < len_nums-3:
if i and nums[i] == nums[i-1]: //去重
i += 1
continue
if nums[i]>target/4.0: //优化
break
j = i+1
while j < len_nums-2:
if j > i+1 and nums[j] == nums[j-1]:
j += 1
continue
if nums[j]>(target-nums[i])/3.0:
break
target_2 = target-nums[i]-nums[j]
left = j+1
right = len_nums-1
if nums[left]>target_2/2.0:
j+=1
continue //此处不能用break
if nums[right]<target_2/2.0:
j+=1
continue
while left < right:
curr = nums[left]+nums[right]
if curr == target_2:
li = [nums[i], nums[j], nums[left], nums[right]]
result.append(li)
while left+1 < len_nums and nums[left] == nums[left+1]: # 去重的同时记得考虑不要越界
left += 1
left += 1
while right-1 > j and nums[right] == nums[right-1]:
right -= 1
right -= 1
elif curr > target_2:
while right-1 > j and nums[right] == nums[right-1]:
right -= 1
right -= 1
else:
while left+1 < len_nums and nums[left] == nums[left+1]:
left += 1
left += 1
j += 1
i += 1
return r