class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
for(int i = 0 ; i < nums.length;i++){
if(i>0 && nums[i-1] == nums[i]){
continue;
}
int left = i+1;
int right = nums.length-1;
while(left<right){
int sum = nums[i] + nums[left] + nums[right];
if(sum>0){
right--;
}else if(sum<0){
left++;
}else{
res.add(new ArrayList<>(Arrays.asList(nums[i],nums[left],nums[right])));
// 去重 left 和 right
while(left<right && nums[left] == nums[left+1]) left++;
while(left<right && nums[right] == nums[right-1]) right--;
left++;
right--;
}
}
}
return res;
}
}
3- ACM 实现
java复制代码
public class threeSum {
public static List<List<Integer>> res = new ArrayList<>();
public static List<List<Integer>> threeSum1(int[] nums){
Arrays.sort(nums);
for(int i = 0 ; i < nums.length;i++){
// 2.1去重i
if(i>0 && nums[i]==nums[i-1]){
continue;
}
//2.双指针
int left = i+1;
int right = nums.length-1;
while (left<right){
int sum = nums[i] + nums[left] + nums[right];
if(sum>0){
right--;
}else if(sum<0){
left++;
}else{
res.add(new ArrayList<>(Arrays.asList(nums[i],nums[left],nums[right])));
while(left<right && nums[left] == nums[left+1]) left++;
while (left<right && nums[right-1] == nums[right]) right--;
left++;
right--;
}
}
}
return res;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入数组长度");
int n = sc.nextInt();
int[] nums = new int[n];
for(int i = 0 ; i < n ;i++){
nums[i] = sc.nextInt();
}
System.out.println("结果是"+threeSum1(nums).toString());
}
}