题目
分析
题没有什么难度,对于几个数之和的问题,就要进行排序,然后就是注意如何进行排查重复,既然是有序的,那么排查重复,就是看当前的和前面一个是否是相同的字符就可以了,三个两个都是这样处理的。
代码实现
import java.util.*;
public class Solution {
public static ArrayList<ArrayList<Integer>> threeSum(int[] num) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
if (num.length < 3) return res;
Arrays.sort(num);
for(int i=0;i<num.length-2;i++)
{
if(i==0||num[i]!=num[i-1])
{
ArrayList<ArrayList<Integer>> temp = twoSum(num, i+1, 0 - num[i]);
if(temp!=null&&temp.size()!=0)
{
for(ArrayList<Integer> e:temp)
{
e.add(num[i]);
Collections.sort(e);
res.add(e);
}
}
}
}
return res;
}
public static ArrayList<ArrayList<Integer>> twoSum(int[] num,int tempindex,int target) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
if (num.length < 2) return res;
int left=tempindex;
int right = num.length - 1;
while (left < right) {
if (num[left] + num[right] > target) {
right--;
} else if (num[left] + num[right] < target) {
left++;
} else {
if(left==tempindex||num[left]!=num[left-1])
{
ArrayList<Integer> temp=new ArrayList<>();
temp.add(num[left]);
temp.add(num[right]);
res.add(temp);
}
right--;
left++;
}
}
return res;
}
}学习情况
1次

京公网安备 11010502036488号