leetcode #18

==============================================================================

【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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值