给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != j、i != k 且 j != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。请
你返回所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/3sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法一:
暴力解法,双指针+排序
class Solution { public List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); List<List<Integer>> ans = new ArrayList<List<Integer>>(); for (int first = 0;first < nums.length; first++){ if (first > 0 && nums[first] == nums[first - 1]){ continue; } int target = - nums[first]; int threed = nums.length-1; for (int second = first + 1;second < nums.length; second++){ if (second > first + 1 && nums[second ] == nums[second - 1]){ continue; } while (second < threed && nums[second] + nums[threed] > target){ --threed; } if (second == threed)break; if (nums[second] + nums[threed] == target){ List<Integer> list = new ArrayList<>(); list.add(nums[first]); list.add(nums[second]); list.add(nums[threed]); ans.add(list); } } } return ans; } }
标签:10,nums,--,list,int,second,threed,letcode,first From: https://www.cnblogs.com/xinger123/p/16656376.html