3Sum

225 篇文章 0 订阅
50 篇文章 0 订阅

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:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • 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)


看到这道题似曾相识,想到了4sum的那个算法。于是就按照那个思路去实现了,然而太naive了,写了个时间复杂度为O(n3)的算法..O(n2)的晚上补充上。


先上O(n3)算法:

package leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ThreeSum {

	public static void main(String[] args) {
		ThreeSum three = new ThreeSum();
		int nums[] = { 1, 2, 3, 4, 5, 6, 7, 9 };
		int num03[] ={9,-4,-5,8,-5,7,5,-6,-4,-13,9,-10,-13,-6,2,-15,-13,-9,-4,-13,-9,-9,13,-13,-9,9,-15,1,0,-14,-8,-13,-11,-5,2,0,9,14,9,-9,8,-5,-12,10,-3,5,3,-1,12,14,1,10,12,-1,13,-12,-14,13,4,-7,6,4,-5,11,6,4,-12,0,3,4,-2,-3,7,1,14,-11,-8,2,-5,11,-7,3,6,-9,9,4,-14,10,-6,-2,-11,-14,-13,-9,4,0,11,-1,-15,-9,-12,-1,3,10,7,-5,6,6,12,8,2,-9,-4,-6,-11,-9,5,-10,-14,-15,3};
		int nums02[] = {};
		int target = 10;
		List<List<Integer>> res = three.threeSum(num03, 0);
		for (List<Integer> list : res) {

			for (Integer integer : list) {
				System.out.print(" " + integer);
			}
			System.out.println();
		}

	}
	public List<List<Integer>> threeSum(int [] nums){
	   return 	threeSum(nums, 0); 
	}

	public List<List<Integer>> threeSum(int[] nums, int target) {
		Arrays.sort(nums);//还是要排序
		// 固定两边,中间的一次循环
	//	int p1 = 0, p2 = nums.length - 1;
		List<List<Integer>> res = new ArrayList<List<Integer>>();
	
	    for(int i=0;i<nums.length-3;i++){
	    	for(int j=nums.length-1;j>=2;j--){
	    		//中间的移动
	    		int k = i+1;
	    		while(k<j){
	    			int tempres = nums[i]+nums[j]+nums[k];
		    		if( tempres == target){
		    			ArrayList<Integer> temp = new ArrayList<Integer>();
		    			temp.add(nums[i]);
		    			temp.add(nums[k]);
		    			temp.add(nums[j]);
		    			if(!res.contains(temp))
		    			res.add(temp);
		    			
		    		}
		    		k++;
	    		}
	    		
	    		
	    	}
	    }

		return res;

	}

}



觉得实现思路跟4sum是类似的,不过固定的是中间的那个数字,先给数组排序,从固定数字的左侧跟右侧扫,如果== target 左右侧各往中间靠近一位;如果小于target则小的一面,也就是左侧的指针向右移动一位;否则,右侧的指针向左移一位。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值