LeetCode----15. 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.

Note: 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]
]

Subscribe to see which companies asked this question

public class Solution {

	public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
		
		ArrayList<ArrayList<Integer>> rst = new ArrayList<ArrayList<Integer>>();
		if(num == null || num.length < 3) {
			return rst;
		}
		Arrays.sort(num);
		for (int i = 0; i < num.length - 2; i++) {
			if (i != 0 && num[i] == num[i - 1]) {
				continue; // to skip duplicate numbers; e.g [0,0,0,0]
			}

			int left = i + 1;
			int right = num.length - 1;
			while (left < right) {
				int sum = num[left] + num[right] + num[i];
				if (sum == 0) {
					ArrayList<Integer> tmp = new ArrayList<Integer>();
					tmp.add(num[i]);
					tmp.add(num[left]);
					tmp.add(num[right]);
					rst.add(tmp);
					left++;
					right--;
					while (left < right && num[left] == num[left - 1]) { // to skip duplicates
						left++;
					}
					while (left < right && num[right] == num[right + 1]) { // to skip duplicates
						right--;
					}
				} else if (sum < 0) {
					left++;
				} else {
					right--;
				}
			}
		}
		return rst;
	}
}

Input: [-1,0,1,2,-1,-4]
Output: [[2,-1,-1]]
Expected: [[-1,-1,2],[-1,0,1]]

Input: [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1],[-1,0,1]]
Expected: [[-1,-1,2],[-1,0,1]]

//此方法时间超时
public class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
       
        
        ArrayList<List<Integer>> ls=new ArrayList<List<Integer>>();
        if(nums.length<3){return ls;}
        Arrays.sort(nums);
        for(int i=0;i<nums.length;i++){
           for(int j=i+1;j<nums.length;j++){
               for(int k=j+1;k<nums.length;k++){
                   if(nums[i]+nums[j]+nums[k]==0){
                       ArrayList<Integer> list=new ArrayList<Integer>();
                       list.add(nums[i]);list.add(nums[j]);list.add(nums[k]);
                       while(!ls.contains(list)){ls.add(list);}
                   }
               }
           } 
        }
        return ls;
    }
}//


Submission Result: Time Limit Exceeded  More Details 
Last executed input: [4,-9,-13,-9,0,-12,12,-14,12,1,3,5,5,8,2,-2,8,1,2,-6,-6,1,6,-15,-2,7,-11,3,-2,1,11,10,8,14,8,-15,9,5,-14,6,14,-3,-12

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值