(头疼,做的时候细节错误百出,然而这只是一道mid难度,在代码中,for循环里可以精简优化一些,指针的排重)
题目:
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: The solution set must not contain duplicate triplets.
意思是给出一个数组,能够组成 a+ b+ c =0的情况,不能重复
思路分析:固定一个值,其他俩指针分别从两边往里循环,要排重。
java代码如下
package LeetCode1;
import java.util.*;
/**
* Created by Wangjianxin on 2017/7/4 0004.
*
*/
public class ThreeSum {
public static void main(String[] args) {
int [] array = {-2,0,0,2,2};
System.out.println(threeSum(array));
}
public static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> list = new LinkedList<List<Integer>>();
int len = nums.length;
//这里需要排序,从小到大,可以用 Arrays.sort(nums);
for(int i =0;i<len ;i++){
for(int j =0;j< len - i -1;j++){
if(nums[j] > nums[j+1]){
int temp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = temp;
}
}
}
System.out.println(Arrays.toString(nums));
if(nums.length == 0 || nums[0] > 0){
return list;
}
//开始循环
for(int i= 0;i<len;i++){
int start = i;
int left = i +1;
int right = len -1;
//排除固定数(start)的重复,除去第一次遍历的时候
if(i > 0 && nums[i] == nums[i-1]){
continue;
}
while (left < right){
int sum = nums[start] + nums[left] + nums[right];
if(sum > 0){
right --;
}
else if(sum < 0){
left ++;
}
//这个是当左指针不能再最左边,时候左指针排重
else if (left != i +1 && nums[left] == nums[left-1]){
left ++;
}
//同理,
else if (right != len -1 && nums[right] == nums[right+1]) {
right --;
}
else{
List<Integer> list1 = new LinkedList<Integer>();
list1.add(nums[start]);
list1.add(nums[left]);
list1.add(nums[right]);
list.add(list1);
//找到后,指针继续往里
left ++;
right --;
}
}
}
return list;
}
}
网友评论