Algorithm deliberate practice -LeetCode actual number of three and 04-

Topic: Three of the number of and

Original title links: (https://leetcode-cn.com/problems/3sum/)
Of course, the method of violence is not to say, it was originally tried a double-pointer, but forgot to determine duplicate programs; plus a repeat determination after the code program, a variety of array bounds error, find the idea of big brother on the "explanations" and found that idea is about the same, but the author is a variety of error:
(first posted this question a tragic history)

Here Insert Picture Description
Here Insert Picture Description
In the end, just shining the code "problem solution" in the bigwigs given "step by step" into a "people's code":

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        vector<vector<int>> ans;
        int n = nums.size();
        if(n < 3) return ans;
        for(int i = 0; i < n - 2; i++)
        {
            if(i == 0 || (i > 0 && nums[i] != nums[i - 1]))
            {
                int L = i + 1, R = n - 1;
                while(L < R)
                {
                    if(nums[i] + nums[L] + nums[R] == 0)
                    {
                        if(L ==  i + 1 || nums[L] != nums[L - 1])
                        {
                            vector<int> v;
                            v.push_back(nums[i]);
                            v.push_back(nums[L]);
                            v.push_back(nums[R]);
                            ans.push_back(v);
                        }
                        L++;
                        R--;
                    }
                    else if(nums[i] + nums[L] + nums[R] < 0)
                    {
                        L++;
                    }
                    else
                    {
                        R--;
                    }
                }
            }
        }
        return ans;
    }
}; 

Digression:

Suffering two types, one that makes you strong; the other is worthless, just inviting torment
- "House of Cards"

Published 16 original articles · won praise 0 · Views 285

Guess you like

Origin blog.csdn.net/DZZ18803835618/article/details/104661935