MySolution in C++


  • 0
    P

    The most import problem thing is that lots of value are equal, so we need to solve this.

    class Solution 
    {
    public:
    	vector<vector<int>> threeSum(vector<int>& nums) 
    	{
    		std::sort(nums.begin(), nums.end());
    		vector<vector<int>> ret;
    		int len = nums.size();
    		for (int i = 0, j = 0, k = len - 1, sum = 0; i < len - 2; ++i) 
    		{
    			if (nums[i] > 0) break;
    			j = i + 1; k = len - 1;
    			while (j < k) 
    			{
    				sum = nums[i] + nums[j] + nums[k];
    				if (sum > 0) --k;
    				else if (sum < 0) ++j;
    				else 
    				{
    					ret.push_back({ nums[i], nums[j], nums[k] });
    					while (nums[j] == nums[j + 1]) ++j;
    					while (nums[k] == nums[k - 1]) --k;
    					++j;
    				}
    			}
    			while (i < len - 3 && nums[i + 1] == nums[i])
    				++i; 
    		}
    		return ret;
    	}
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.