【LeetCode】15. 三数之和(Java)

    科技2022-08-27  97

    给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。

    注意:答案中不可以包含重复的三元组。

    class Solution { public List<List<Integer>> threeSum(int[] nums) { //三指针i,left,right List<List<Integer>> res = new ArrayList<>(); //特判 if (nums == null || nums.length < 3) return res; //对数组进行排序 Arrays.sort(nums); for (int i = 0; i < nums.length - 2; i++) { //因为我们已经对数组进行排序了,所以如果第一层循环的值都大于0,跳出循环 //这里用减法,可以避免相加太大而溢出 if (nums[i] > 0 && nums[i] >= 0) break; //如果当前值不是第一个值,那么就判断当前值是否和上一个值一样,一样则跳过 if (i > 0 && nums[i] == nums[i - 1]) continue; //双指针 int left = i + 1, right = nums.length - 1; while (left < right) { //四数相加后小于目标值,左指针向右移一位 if (nums[i] + nums[left] + nums[right] < 0) left++; //相加后大于目标值,右指针向左移一位 else if (nums[i] + nums[left] + nums[right] > 0) right--; //如果等于目标值 else { res.add(Arrays.asList(nums[i], nums[left], nums[right])); //往left往右移一位,如果和重复,继续移动 left++; while (left < right && nums[left] == nums[left - 1]) left++; right--; while (left < right && nums[right] == nums[right + 1]) right--; } } } return res; } }

    做完18. 四数之和反回来做三数和就简单了,代码稍微改一下即可。

    Processed: 0.012, SQL: 9