1. 程式人生 > >【LeetCode】#15三數之和(3Sum)

【LeetCode】#15三數之和(3Sum)

【LeetCode】#15三數之和(3Sum)

題目描述

給定一個包含 n 個整數的陣列 nums,判斷 nums 中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?找出所有滿足條件且不重複的三元組。
注意:答案中不可以包含重複的三元組。

示例

例如, 給定陣列 nums = [-1, 0, 1, 2, -1, -4],
滿足要求的三元組集合為:
[
[-1, 0, 1],
[-1, -1, 2]
]

Description

Given an array nums of n integers, are there elements a, b, c 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]
]

解法

class Solution{
	public List<List<Integer>> threeSum(int[] nums){
		Arrays.sort(nums);
		int iNum = Integer.MAX_VALUE;
		int jNum;
		int kNum;
		List<List<Integer>> res = new ArrayList<>();
		for(int i=0; i<nums.length && nums[i]<0; i++){
			if(iNum==nums[i]){
				continue;
			}
			iNum = nums[i];
			int j = i + 1;
			int k = nums.length-1;
			while(j<k){
				int sum = nums[i] + nums[j] + nums[k];
				if(sum>0){
					k--;
				}else if(sum<0){
					j++;
				}else{
					List<Integer> list = new ArrayList<>();
					list.add(nums[i]);
					list.add(nums[j]);
					list.add(nums[k]);
					res.add(list);
					jNum = nums[j];
					do{
						j++;
						if(j>=k){
							break;
						}
					}while(jNum==nums[j]);
					kNum = nums[k];
					do{
						k--;
						if(j>=k){
							break;
						}
					}while(kNum==nums[k]);
				}
			}
		}
		return res;
	}
}