leetcode 3sum

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


题意:给定一个数组num,求数组中三个数字相加为0的所有组合

思路:和上一篇twoSum类似,注意不同的地方。twoSum解是唯一的,而3sum不一定是唯一的

           基本的想法还是暴力搜索,时间复杂度O(n^3),不是理想的答案

           由于3sum是建立在twoSum的基础上的,可以选择固定一个数字,让余下的数字进行twoSum的操作。

           和twoSum不一样的地方是,twoSum使用了hashMap,在3sum中当然也可以使用HashMap,但是用hashMap有一个重复解的问题(twoSum只有一个解,所以不考虑重复解问题)。这里使用一种更好的方法,头尾指针法,前提是要进行排序,排序后让两个指针分别指向数组的头和尾,不断往中间移动两个指针,获取到所有的解,代码如下:

import java.util.ArrayList;
import java.util.Arrays;
public class Solution {
    private ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
    public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
        Arrays.sort(num);
    	for(int i = 0;i<num.length-2;i++)
    	{
            if(i>0 && num[i] == num[i-1])
    			continue;
    		threeSumHelp(num[i],num,i+1);
    	}
    	return result;
    }
    public void threeSumHelp(int value,int[] num,int low)
    {
    	int target = 0 - value;
    	int high = num.length-1;
    	while(low<high)
    	{
    		if(num[low] + num[high] == target)//获得了一个解
    		{
    			ArrayList<Integer> ans = new ArrayList<Integer>();
    			ans.add(value);
    			ans.add(num[low]);
    			ans.add(num[high]);
    			result.add(ans);
    			low++;
    			high--;
    			while(num[low] == num[low-1] && low<=high)
    				low++;
    			while(num[high] == num[high+1] && low<=high)
    				high--;
    		}
    		else if(num[low] + num[high]>target){
				high--;
			}
    		else {
    			low++;
			}
    	}
    }
}


时间复杂度为 排序O(nlogn) + O(n^2) = O(n ^ 2 )

由于排序的时间复杂度低于 O(n^2),因此先进行排序再作处理。这样在不耗费空间的前提下,完成程序。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值