• 3Sum——LeetCode


    Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

    Note:

    • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
    • The solution set must not contain duplicate triplets.
        For example, given array S = {-1 0 1 2 -1 -4},
    
        A solution set is:
        (-1, 0, 1)
        (-1, -1, 2)

    题意是给定一个数组,找出来三元组之和等0,找出所有的组合并且不重复以字典序输出。

    大体思路就是,先给数组排序,然后对数组中的前n-2个元素依次遍历,为啥是前n-2个元素,因为遍历到第n-2个元素时,只剩下第n-1和第n个元素来组成三元组了。

    遍历的时候,有left和right两个游标,left就从i+1开始,right就从数组最右length-1开始,如果i、left、right三个元素加起来等0,那么就可以加入结果的List中了,如果<0,那么说明负数的绝对值比正数大,left应该向右移动,反之right向左移动。

    注意,因为题目要求重复的组合不输出,那么遍历的时候要注意跳过相同的元素。

    Talk is cheap>>

      public List<List<Integer>> threeSum(int[] num) {
            List<List<Integer>> res = new ArrayList<>();
            if (num == null || num.length < 3) {
                return res;
            }
            Arrays.sort(num);
            if (num[0] > 0 || num[num.length - 1] < 0)
                return res;
            for (int i = 0; i < num.length - 2; i++) {
                if (i != 0 && num[i] == num[i - 1]) {
                    continue;
                }
                int left = i + 1, right = num.length - 1;
                while (left < right) {
                    int sum = 0;
                    List<Integer> tmp = new ArrayList<>();
                    sum = num[i] + num[left] + num[right];
                    if (sum == 0) {
                        tmp.add(num[i]);
                        tmp.add(num[left]);
                        tmp.add(num[right]);
                        res.add(tmp);
                        while (left < right && num[left] == num[left + 1]) {
                            left++;
                        }
                        while (left < right && num[right] == num[right - 1]) {
                            right--;
                        }
                        left++;
                        right--;
                    } else if (sum < 0) {
                        left++;
                    } else {
                        right--;
                    }
                }
            }
            return res;
        }
  • 相关阅读:
    hashCode花式卖萌
    2017年的小总结
    多线程环境下的单例模式
    Servlet过滤器简单探索
    最长回文子序列(LPS)
    最短编辑距离问题
    赫夫曼编码
    DNA序列对齐问题
    同时寻找序列的最大最小值
    最长公共子序列(LCS)
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4376251.html
Copyright © 2020-2023  润新知