LeetCode----15.三數之和
阿新 • • 發佈:2020-07-17
題目描述
給你一個包含 n 個整數的陣列 nums,判斷 nums 中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?請你找出所有滿足條件且不重複的三元組。
注意:答案中不可以包含重複的三元組。
示例
給定陣列 nums = [-1, 0, 1, 2, -1, -4],
滿足要求的三元組集合為:
[
[-1, 0, 1],
[-1, -1, 2]
]
思路
初步思路:看作 b + c = -a,變成找2數之和為 -a 的 2 個數
程式碼
class Solution { public List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); List<List<Integer>> ans = new LinkedList<>(); Map<Integer, Integer> map = new HashMap<>(); for(int i : nums) { if(map.containsKey(i)) { map.put(i, map.get(i)+1); } else { map.put(i, 1); } } for(int i = 0; i < nums.length; ++i) { if(i > 0 && nums[i] == nums[i-1]) { map.put(nums[i], map.get(nums[i])-1); continue; } int sum = -nums[i]; map.put(nums[i], map.get(nums[i])-1); Set<Integer> set = new HashSet<>(); for(int j = i+1; j < nums.length; ++j) { if(set.contains(nums[j])){ continue; } int t = sum - nums[j]; map.put(nums[j], map.get(nums[j])-1); if(map.containsKey(t) && map.get(t) > 0) { set.add(nums[j]); set.add(t); List<Integer> list = new LinkedList<>(); list.add(nums[i]); list.add(nums[j]); list.add(t); ans.add(list); } map.put(nums[j], map.get(nums[j])+1); } } return ans; } }