1. 程式人生 > 其它 >15 三數之和(LeetCode HOT 100)

15 三數之和(LeetCode HOT 100)

描述:
給你一個包含 n 個整數的陣列 nums,判斷 nums 中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?請你找出所有和為 0 且不重複的三元組。

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

示例 1:

輸入:nums = [-1,0,1,2,-1,-4]
輸出:[[-1,-1,2],[-1,0,1]]

示例 2:

輸入:nums = []
輸出:[]

示例 3:

輸入:nums = [0]
輸出:[]

提示:
0 <= nums.length <= 3000
-105 <= nums[i] <= 105

Soulution:

    public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> results = new ArrayList<>();
        // 使用雜湊表,O(1)查詢想要的數字
        HashMap<Integer, Integer> numMap = new HashMap<>(nums.length);

        // 因為不允許出現重複答案,一個元素最多出現三次,大於三次的數字是無用的,可剔除
        List<Integer> filterList = new ArrayList<>();
        for (int num : nums) {
            Integer count = numMap.getOrDefault(num, 0);
            if (count < 3) {
                filterList.add(num);
                numMap.put(num, (count + 1));
            }
        }

        for (int i = 0; i < filterList.size(); ++i) {
            numMap.put(filterList.get(i), i);
        }
        for (int i = 0; i < filterList.size(); ++i) {
            for (int j = i + 1; j < filterList.size(); ++j) {
                int a = filterList.get(i);
                int b = filterList.get(j);
                int c = -a - b;
                Integer index = numMap.get(c);
                if (index != null && index != i && index != j) {
                    List<Integer> result = new ArrayList<>(Arrays.asList(a, b, c));
                    Collections.sort(result);
                    results.add(result);
                }
            }
        }
        // 去重
        return results.stream().distinct().collect(Collectors.toList());
    }

Idea:
使用雜湊表,O(1)查詢想要的數字
因為不允許出現重複答案,一個元素最多出現三次,大於三次的數字是無用的,可剔除,減少資料規模

Reslut:

Impore:
可以使用排序+雙指標優化。