力扣(LeetCode)15. 三數之和
阿新 • • 發佈:2019-04-05
-- 整數 -c 去重 clas pub lis inf 分享
給定一個包含 n 個整數的數組 nums,判斷 nums 中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?找出所有滿足條件且不重復的三元組。
註意:答案中不可以包含重復的三元組。
例如, 給定數組 nums = [-1, 0, 1, 2, -1, -4],
滿足要求的三元組集合為:
[
[-1, 0, 1],
[-1, -1, 2]]
思路 用HashSet無重復的特點去重。
先將數組排序。 Arrays.sort(nums); //從小到大
用三個指針,i指向第一個元素,j指向第二個元素,k指向第三個元素。
java版
class Solution { public List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); List<List<Integer>> list = new ArrayList<List<Integer>>(); HashSet<List<Integer>> hashset = new HashSet<>(); int i,j,k,len = nums.length; for(i=0;i<len-2;i++) { j = i+1; k = len-1; while(j < k) { int sum = nums[i]+nums[j]+nums[k]; if(sum < 0) { j++; }else if(sum > 0) { k--; }else { List<Integer> list1 = new ArrayList<>(); list1.add(nums[i]); list1.add(nums[j]); list1.add(nums[k]); hashset.add(list1); j++; k--; } } } if(hashset.size()!=0) { Iterator<List<Integer>> iterator = hashset.iterator(); while(iterator.hasNext()) { list.add(iterator.next()); } } return list; } }
運行結果
力扣(LeetCode)15. 三數之和