您的位置:首页 > 其它

leetcode 15. 3Sum

2016-05-04 11:48 288 查看
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;

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

public class Solution {

public static void main(String[] args) {
int[] a = {-1,0,1,2,-1,-4};
List<List<Integer>> result = threeSum(a);
System.out.println(result);
}

public static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
Arrays.sort(nums);
for(int i = 0;i<nums.length-2;i++){										//遍历数组
int j = i+1;
int end = nums.length-1;
if(i>0&&nums[i] == nums[i-1]){
continue;
}
while(j<end){														//从当前元素之后的两头寻找与其之和为0的两个元素
if(nums[i]+nums[j]+nums[end] == 0){
List<Integer> a = new ArrayList<Integer>();
a.add(nums[i]);
a.add(nums[j]);
a.add(nums[end]);
result.add(a);
while(nums[end-1] == nums[end]&&end>j){						//若有相同元素,则直接跳过
end--;
}
while(nums[j+1] == nums[j]&&j<end){
j++;
}
end--;
j++;
}else if(Math.abs(nums[i])<Math.abs(nums[j]+nums[end])){							//若相加不为0,则根据情况调整两端位置
end--;
}else{
j++;
}

}
}
return result;
//        List<List<Integer>> result = new ArrayList<List<Integer>>();				//容易理解但是超时的做法
//        Arrays.sort(nums);
//        for(int i = 0;i<nums.length-2;i++){
//        	if(i>0&&nums[i] == nums[i+1]){
//        		continue;
//        	}
//        	for(int j = i+1;j<nums.length-1;j++){
//        		if(j>1&&nums[j] == nums[j+1]){
//            		continue;
//            	}
//        		for(int k = j+1;k<nums.length;k++){
//        			if(nums[i]+nums[j]+nums[k] == 0){
//        		        List<Integer> a = new ArrayList<Integer>();
//
//        				a.add(nums[i]);
//        				a.add(nums[j]);
//        				a.add(nums[k]);
//        				result.add(a);
//        				break;
//        			}
//        		}
//        	}
//        }
//
//        for(int i = 0;i<result.size()-1;i++){
//        	if(result.get(i).equals(result.get(i+1))){
//            	result.remove(i+1);
//            }
//        }
//        return result;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: