• LeetCode 15


    一、问题描述

    Description:

    Given an array S of n integers, are there elements a, b, c 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)

    给定一个包含 n 个整数的数组,找出其中所有和为 0 的三元组。

    注意:

    • 每个三元组中的三个数按大小顺序排列,abc
    • 返回的三元组不能重复。


    二、解题报告

    首先,不用考虑暴力解法了,三层循环时间复杂度是O(n3),而且还要处理重复的问题,必然会超时。

    3Sum 问题可以在 2Sum 的基础上求解,也就是先固定一个数,然后转化为求2Sum。

    在《LeetCode 1 - Two Sum》中我们讲了2Sum问题的两种解法。在这里,采用头尾指针求2Sum。

    求3Sum的思路如下:

    • 先整体排一次序
    • 然后遍历数组,固定一个元素,对其后的元素求2Sum。

    比如排好序以后的数字是 a b c d e f, 那么第一次固定a, 在剩下的 b c d e f 中进行2sum, 完了以后第二次枚举b, 只需要在 c d e f 中进行2sum,这样就避免了重复。

    代码如下:O(n2)

    class Solution {
    public:
        vector<vector<int>> res;
    
        vector<vector<int>> threeSum(vector<int>& nums) {
            if(nums.size() < 3) 
                return res;
            sort(nums.begin(), nums.end());   // 排序
    
            for(int i=0; i<nums.size()-2; ++i) {
                if(i>0 && nums[i]==nums[i-1]) // 相等的跳过
                    continue;
                twoSum(nums, i+1, nums.size()-1, nums[i]);
            }
            return res;
        }
    
        void twoSum(vector<int>& nums, int begin, int end, int target) {
            int i = begin;  // 头指针
            int j = end;    // 尾指针
            while(i < j) {
                if(nums[i]+nums[j]+target==0) {
                    vector<int> v;
                    v.push_back(target);
                    v.push_back(nums[i]);
                    v.push_back(nums[j]);
                    res.push_back(v);
                    while(i<j && nums[i]==nums[i+1]) 
                        ++i;  // 相等的跳过
                    while(i<j && nums[j]==nums[j-1]) 
                        --j;  // 相等的跳过
                    ++i;
                    --j;
                }
                else if(nums[i]+nums[j]+target<0)
                    ++i;
                else
                    --j;
            }
        }
    };


    其实 K Sum 是一类问题,是经典的面试题,主要是考察是否能够合理利用排序这个性质,一步一步得到高效的算法。这里总结的比较完整,可以看看。





    LeetCode答案源代码:https://github.com/SongLee24/LeetCode


  • 相关阅读:
    Controller返回值string、mv等区别
    CA证书目的和详细演化过程
    HashMap和Hashtable的区别
    操作系统-IO管理疑难点
    IO核心子系统
    操作系统-IO管理概述
    文件管理疑难点
    磁盘组织与管理
    文件系统实现
    文件系统基础
  • 原文地址:https://www.cnblogs.com/songlee/p/5738052.html
Copyright © 2020-2023  润新知