O(n^2) solution but times out on [0,0,0]? why?


  • 0
    N
    vector<vector<int>> threeSum(vector<int>& nums) {
        sort(nums.begin(),nums.end());
        vector<vector<int>> result;
        if (nums.size() < 3){
            return result;   
        }
        for (int i = 0; i < nums.size()-2; i++){
            int j = i+1;
            int k = nums.size()-1;
            while (j < k){
                int sum = nums[i] + nums[j] + nums[k];
                if (sum == 0){
                    vector<int> temp;
                    temp.push_back(nums[i]);
                    temp.push_back(nums[j]);
                    temp.push_back(nums[k]);
                    result.push_back(temp);
                }else if(sum < 0){
                    j++;
                }else if(sum > 0){
                    k--;
                }
            }
        }
        return result;
    }

  • 0
    Y

    "if(sum==0)",you should add "j++;k--;",otherwise you will get struck into an infinite loop;


Log in to reply
 

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