leetcode第15题——**3Sum

25 篇文章 0 订阅
25 篇文章 0 订阅

题目

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

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie,abc)
  • The solution set must not contain duplicate triplets.
    For example, given array S = {-1 0 1 2 -1 -4},

    A solution set is:
    (-1, 0, 1)
    (-1, -1, 2)

思路

这是Ksum类的问题,求出数组中K个数满足和为target的值。这一类问题都有类似解法。

可以先把数组非递减排序,然后从头到尾遍历数组,每次固定一个数nums[a],然后就是从剩下的数当中找到和为-nums[a]的两个数,由于数组是有序的,可以从头尾分别往中间靠拢,这样找两个和为-nums[a]的时间复杂度为o(n)

排序的时间复杂度为O(nlgn),找出数据并去重的时间复杂度为O(n^2),整体时间复杂度为O(nlgn)+O(n^2),当n很大时时间复杂度为O(n^2)

代码

Python
class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        leng = len(nums)
        res = []
        if (nums == None or leng < 3):
            return res
            
        nums.sort()
        for a in xrange(leng):
            #去重
            if (a > 0 and nums[a] == nums[a-1]):
                continue
            
            b = a + 1;
            c = leng - 1;
            while(b < c):
                tsum = nums[a] + nums[b] + nums[c]
                if (tsum < 0):
                    #头指针往前移动
                    b += 1
                elif (tsum > 0):
                    #尾指针往后移动
                    c -= 1
                else:
                    item = []
                    item.append(nums[a])
                    item.append(nums[b])
                    item.append(nums[c])
                    res.append(item)
                    
                    #如果有相等数字,则头尾指针要移动(去重)
                    while(True):
                        b += 1
                        if (b < c and nums[b-1] == nums[b]):
                            continue
                        else:
                            break
                    while(True):
                        c -= 1
                        if (c > b and nums[c+1] == nums[c]):
                            continue
                        else:
                            break
                        
        return res                        

Java

public class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if (nums == null || nums.length < 3) return res;
        //先对数组排序
        Arrays.sort(nums);
        
        int len = nums.length;
        int a,b,c,sum;
        for(a = 0; a < len; a++){
        	//去重
        	if(a > 0 && nums[a] == nums[a-1]) continue;
        	
        	b = a + 1;
        	c = len - 1;
        	while(b < c){
        		sum = nums[a] + nums[b] + nums[c];
        		
        		if(sum < 0) b++;//如果sum太小,头指针往后移动,找更大的数
        		else if(sum > 0) c--;//如果sum太大,尾指针往前移动 			
        		else{
        			List<Integer> item = new ArrayList<Integer>();
        			item.add(nums[a]);
        			item.add(nums[b]);
        			item.add(nums[c]);
        			res.add(item);
        			
        			while((b+=1) < c && nums[b-1] == nums[b]){
        				continue;
        			}
        			while((c-=1) > b && nums[c+1] == nums[c]){
        				continue;
        			}
        		}
        	}
        	
        }        
	return res;
    }
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值