N

(Leet Code c++)3Sum 본문

Leet Code 알고리즘

(Leet Code c++)3Sum

naeunchan 2021. 8. 10. 10:46
728x90
반응형

15. 3Sum

 

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.

 

Example 1:

Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]]

Example 2:

Input: nums = [] Output: []

Example 3:

Input: nums = [0] Output: []

 

Constraints:

  • 0 <= nums.length <= 3000
  • -105 <= nums[i] <= 105
class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> answer;
        int size = nums.size();
        
        if(nums.size() < 3){
            return {};
        }
        
        sort(nums.begin(), nums.end());
        
        for(int i = 0; i < size - 2; i++){
            if(i > 0 && nums[i] == nums[i - 1]){
                continue;
            }
            
            int j = i + 1;
            int k = size - 1;
            
            while(j < k){
                int sum = nums[i] + nums[j] + nums[k];
                
                if(sum == 0){
                    answer.push_back({nums[i], nums[j], nums[k]});
                    
                    while(j < k && nums[j] == nums[j + 1]){
                        j++;
                    }
                    
                    while(j < k && nums[k] == nums[k - 1]){
                        k--;
                    }
                    
                    j++;
                    k--;
                }
                else if(sum < 0){
                    j++;
                }
                else{
                    k--;
                }
            }
        }
        
        return answer;
    }
};
728x90
반응형