C++ Solution(52ms), How to run fast?


  • 0
    Q
    class Solution {
    public:
    	vector<vector<int>> threeSum(vector<int>& nums) {
    		vector<vector<int>> result;
    		if (nums.size()<3) return result;
    
    		int target = 0;
    		int tmpNum = 0;
    		// index is not need, but sorted is need
    		std::sort(nums.begin(), nums.end());
    		int count = nums.size();
    		vector<int> tmp(5);
    
    		for (int i = 0; i<count - 2;) {
    			// the sum is 0, so the first num must not larger than 0
    			if (nums[i] > 0) break;
    			int j = i + 1;
    			int k = count - 1;
    			// the sum is 0, so the last num must not smaller than 0
    			if (nums[k] < 0) break;
    			while (j<k) {
    				// the sum is 0, so the last num must not smaller than 0
    				if (nums[k] < 0) break;
    				int sum = nums[i] + nums[j] + nums[k];
    				if (sum == 0)
    				{
    					tmp.clear();
    					tmp.push_back(nums[i]);
    					tmp.push_back(nums[j]);
    					tmp.push_back(nums[k]);
    					result.push_back(tmp);
    					// change j to nums[j] != nums[old j]
    					do {
    						j++;
    					} while (j<k && nums[j] == nums[j - 1]);
    					// change k to nums[k] != nums[old k]
    					do {
    						k--;
    					} while (j<k && nums[k] == nums[k + 1]);
    				}
    				else if (sum > 0) {
    					// change k to nums[k] != nums[old k]
    					do {
    						k--;
    					} while (j<k && nums[k] == nums[k + 1]);
    				}
    				else {
    					// change j to nums[j] != nums[old j]
    					do {
    						j++;
    					} while (j<k && nums[j] == nums[j - 1]);
    				}
    			}
    			// change i to nums[i] != nums[old i]
    			do {
    				i++;
    			} while (i<count - 2 && nums[i] == nums[i - 1]);
    		}
    		return result;
    	}
    };

Log in to reply
 

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