LeetCode 15. 3Sum three and the number of

Topic links: Click here
Here Insert Picture Description

The key solution is to remove repeated, map marking out.

Japanese sentence, if the length is less than the array 3 3 , return [   ] [\ ]

Sort the array.

The first digit enumeration n in m s [ i ] nums[i] , the double pointer to find a two-digit n in m s [ L ] nums[L] and n in m s [ R ] nums[R]

  • If the n in m s [ i ] > 0 nums[i]>0 : as it has been sorted, so there can not be equal to three and the number of 0 0 , exit.
  • For repeating elements: skipped, to avoid duplication Solutions

Make a left pointer L = i + 1 L=i+1 , the right pointer R = n 1 R=n−1 , when L < R L<R , the execution cycle:

  • when n in m s [ i ] + n in m s [ L ] + n in m s [ R ] = = 0 nums[i]+nums[L]+nums[R]==0 , execution cycle, and determines whether or not the left boundary and the right boundary position of the next repeat, deduplication solution. And at the same time L , R L,R to the next position, looking for new solutions
  • If greater than 0 0 , indicating n u m s [ R ] nums[R] is too large, R R Left
  • If less than 0 0 , indicating n u m s [ L ] nums[L] is too small, L L right
class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> ans;
        sort(nums.begin(), nums.end());
        int n = nums.size();
        
        for(int i = 0; i < n; ++i)
        {
            if(nums[i] > 0)	break;	//若此处大于0,后面不可能找到负数了
            if(i > 0 && nums[i] == nums[i-1])   continue;	//去重 
            
            int pivot = -nums[i];
            int L = i + 1, R = n - 1;
            
            while(L<R)
            {
                if(nums[L]+nums[R]==pivot)
                {
                    ans.push_back({nums[i],nums[L],nums[R]});
                    ++L;
					--R; 
                    while(L < R && nums[L] == nums[L-1])
                    	++L;
                    while(L < R && nums[R] == nums[R+1])
                    	--R;
                }
                else if(nums[L]+nums[R] < pivot)
                {
                    ++L;
                }
                else
                {
                    --R;
                }
            }
        }
        return ans;
    }
};
Published 727 original articles · won praise 111 · views 120 000 +

Guess you like

Origin blog.csdn.net/qq_42815188/article/details/104317971