[LeetCode] 3Sum 解题思路

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 的三个元素。

解题思路:

自己想了一个解法,但是扔上去超时了,然后在网上看到使用双指针的算法,理解后,把这道题解决了。

第一步,对数组排序。

第二步,

分析1:对于元素 S[i] , 最后的答案可以分为两种,包含 S[i] 的,和不包含 S[i] 的。当包含 S[i] 的情况都找到后,后续就可以不用在考虑 S[i] 。

对于 S[i] , l = i+1, r = len-1 。若 s[i] + S[l] + S[r] == 0, 则为原问题的一个解。

  • 当 S[i] + S[l] > -S[r] 时,则 r--
  • 当 S[i] + S[l] < -S[r] 时,则 l++
  • 当 S[i] + S[i] = -S[r] 时, 表示是原问题的一个解,则 l++, r--;

第三步,性能优化。同样根据分析1,若 S[i] == S[i+1],可以跳过。

vector<vector<int>> threeSum(vector<int>& nums) {

    vector<vector<int>> res;

    std::sort(nums.begin(), nums.end());

    map<string, vector<int>> key_res;

    for (int i = 0 ; i < (int)nums.size(); i++) {

        // star 剪枝优化
        if (i >= 1) {
            while (nums[i] == nums[i-1]) {
                i++;
                continue;
            }
        }
        // end 剪枝优化

        int l = i+1;
        int r = (int)nums.size()-1;

        while (l < r) {
            if (nums[l] + nums[r] > -nums[i]) {
                r--;
                continue;
            }
            else if (nums[l] + nums[r] < -nums[i]){
                l++;
            }else{
                string k = to_string(nums[i]) + "," + to_string(nums[l]) + "," + to_string(nums[r]);

                vector<int> tmp = {nums[i], nums[l] , nums[r]};
                key_res[k] = tmp;

                l++;
                r--;
            }
        }
    }

    map<string, vector<int>>::iterator m_iter;
    for (m_iter = key_res.begin(); m_iter != key_res.end(); m_iter++) {
        res.push_back(m_iter->second);
    }

    return res;
}
时间: 2024-12-14 06:05:51

[LeetCode] 3Sum 解题思路的相关文章

[LeetCode]3Sum,解题报告

题目 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 so

leetcode每日解题思路 221 Maximal Square

问题描述: 题目链接:221 Maximal Square 问题找解决的是给出一个M*N的矩阵, 只有'1', '0',两种元素: 需要你从中找出 由'1'组成的最大正方形.恩, 就是这样. 我们看到, 这道题目的标签还是DP, 那么问题的关键就是要找到一个符合判断是否为正方形的递推式. 老套路, 先看基本型, 对于一个2*2的正方形,对于右下角的元素(1,1)而言, 他的上(0,1), 左(1,0), 左上(0,0)三个元素应该都是'1', 如此才能够组成一个合规的正方形: 那么如果是一个3*

[LeetCode] Word Break 解题思路

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. For example, givens = "leetcode",dict = ["leet", "code"]. Return true because &

[LeetCode] Longest Valid Parentheses 解题思路

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. For "(()", the longest valid parentheses substring is "()", which has length = 2. Another example is &

[LeetCode] Minimum Size Subarray Sum 解题思路

Given an array of n positive integers and a positive integer s, find the minimal length of a subarray of which the sum ≥ s. If there isn't one, return 0 instead. For example, given the array [2,3,1,2,4,3] and s = 7,the subarray [4,3] has the minimal

LeetCode解题思路:595. Big Countries

There is a table World +-----------------+------------+------------+--------------+---------------+ | name | continent | area | population | gdp | +-----------------+------------+------------+--------------+---------------+ | Afghanistan | Asia | 652

leetCode 103.Binary Tree Zigzag Level Order Traversal (二叉树Z字形水平序) 解题思路和方法

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). For example: Given binary tree {3,9,20,#,#,15,7}, 3 / 9 20 / 15 7 return its zig

[LeetCode] 53. Maximum Subarray 解题思路

Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [-2,1,-3,4,-1,2,1,-5,4],the contiguous subarray [4,-1,2,1] has the largest sum = 6. 问题: 给定一个元素有正有负的数组,求最大连续子数组的和. 思路

[LeetCode] Maximum Gap 解题思路

Given an unsorted array, find the maximum difference between the successive elements in its sorted form. Try to solve it in linear time/space. Return 0 if the array contains less than 2 elements. You may assume all elements in the array are non-negat