先看一下两数之和的解:
给一个有序数组,返回组成和为指定值的元组
public static void main(String[] args) {
int[] arr={2, 2 ,4, 5 ,9 ,10 ,12};
getPair(arr,14);
}
public static void getPair(int[] nums,int aim){
if(nums==null||nums.length<2){
return;
}
int L=0;
int R=nums.length-1;
while (L<R){
//arr[L]+arr[R]> R-- < L++
if(nums[L]+nums[R]>aim){
R--;
}else if(nums[L]+nums[R]<aim){
L++;
}else{
if(L==0||nums[L-1]!=nums[L]){//避免重复值
System.out.println("left="+nums[L]+",right="+nums[R]);
}
L++;
R--;
}
}
}
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例 1:
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
// -4 -1 -1 0 1 2
List<List<Integer>> resultList=new ArrayList<>();
if(nums==null || nums.length<3){
return resultList;
}
Arrays.sort(nums);
for(int i=0;i<nums.length-2;i++){
if(nums[i]>0){
return resultList;
}
if(i>0 && nums[i]==nums[i-1]){
continue;
}
int target=-nums[i];
int L=i+1;
int R=nums.length-1;
while(L<R){
if(nums[L]+nums[R]==target){
List<Integer> ans=new ArrayList<>();
ans.add(nums[i]);
ans.add(nums[L]);
ans.add(nums[R]);
resultList.add(ans);
L++;
R--;
while(L<R && nums[L]==nums[L-1]){
L++;
}
while(L<R && nums[R]==nums[R+1]){
R--;
}
}else if (nums[L]+nums[R]<target){
L++;
}else{
R--;
}
}
}
return resultList;
}
}
原文:https://www.cnblogs.com/iwyc/p/15253332.html