LeetCode 15. 3Sum

问题

Given an array nums of n integers, are there elements abc in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

The solution set must not contain duplicate triplets.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

分析

先对数组nums排序,然后固定第一个数a,则问题可以转化为在比a大的元素中,找到b, c,使得b + c = -a, 所以我们可以使用2sum的解法遭到b, c。

a有n个取值,2sum的时间复杂度为O(n), 所以3sum的时间复杂度为O(n^{2})

如果需要去重,可以使用集合去除重复的a,b,c

伪代码

3Sum(nums)
sort nums by ascending order
initialize set s
n = nums.length
for i = 1 to n - 2
    a = nums[i]
    left = i + 1
    right = n
    while left < right
        if nums[left] + nums[right] < -a
            left = left + 1
        elseif nums[left] + nums[right] > -a
            right = right - 1
        else
            add a,b,c to s
            left = left + 1
            right = right - 1
initialize array result and fill result with elements of s
return result
            

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值