leecode算法《15. 三数之和》详解有注释,简单明了。
原题内容
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法一:
这个解法是不推荐的,只是博主辛辛苦苦写出来了需要说一下
思路是将三数之和转化为2数之和
a+b+c=0 ==>a+b=-c
根据以上公式 三数之和就变成了两数之和了
需要循环数组,取出每一个值作为-c,再在原数组中找两数之后等于-c的就OK了;
这种方法的难点是结果集去重;
我代码写出来了,但是leecode上执行超时,所以不推荐。
代码
public static List<List<Integer>> threeSum(int[] nums) {
if (nums.length < 3) {
return new ArrayList<>();
}
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
List<List<Integer>> c = threeTwo(nums, -nums[i], i);
for (int t = 0; t < c.size(); t++) {
boolean add = true;
for (int y = 0; y < result.size(); y++) {
List<Integer> integers = c.get(t);
List<Integer> c1 = result.get(y);
if (integers.get(0).equals(c1.get(0)) && integers.get(1).equals(c1.get(1)) && integers.get(2).equals(c1.get(2))) {
add = false;
}
}
if (add) {
result.add(c.get(t));
}
}
}
return result;
}
public static List<List<Integer>> threeTwo(int[] nums, int target, int j) {
List<List<Integer>> result = new ArrayList<>();
Map<Integer, Integer> map = new HashMap<>(16);
for (int i = 0; i < nums.length; i++) {
List<Integer> list = new ArrayList<>();
if (map.get(nums[i]) != null && i != j) {
list.add(nums[i]);
list.add(map.get(nums[i]));
list.add(-target);
Collections.sort(list);
result.add(list);
} else {
if (i != j) {
map.put(target - nums[i], nums[i]);
}
}
}
return result;
}
解法二
我反正是比较笨的。没有想到用双指针的方法
双指针的方法确实比较帅;
思路:
图解:
代码接加注释,逻辑非常清楚
public static List<List<Integer>> threeSum4(int[] nums) {
// 先对数字进行排序
Arrays.sort(nums);
// 创建一个集合来存储结果集
List<List<Integer>> result = new ArrayList<>();
// 求出数组的长度
int length = nums.length;
for (int k = 0; k < length - 2; k++) {
// 如果需要循环的数》0,那么一定不会有三个数相加等于0的,直接跳出循环
if (nums[k] > 0)break;
// 如果这次循环的数和上一个循环的数重复,直接跳过,防止结果集中出现重复的值
if (k > 0 && nums[k] == nums[k - 1])continue;
// 定义两个指针。i指向K的上一个数字,j指向数组的最后一个数字
int i = k + 1;
int j = length - 1;
while (i < j) {
// 求出三个数的和
int sum = nums[k] + nums[i] + nums[j];
if (sum < 0) {
// 如果结果《0,i++; 下面这句代码不理解的话,需要去查++i和i++的区别
while (i < j && nums[i] == nums[++i]) ;
} else if (sum > 0) {
// 如果结果>0,j--;
while (i < j && nums[j] == nums[--j]) ;
} else {
// 如果结果=0,将结果存入集合中;并且I++;J--
result.add(new ArrayList<>(Arrays.asList(nums[k], nums[i], nums[j])));
while (i < j && nums[i] == nums[++i]) ;
while (i < j && nums[j] == nums[--j]) ;
}
}
}
return result;
}