simple extension of two pointers, no need for hashmaps


  • 0

    class Solution {

    public:
    vector<vector<int>>res;

    vector<vector<int>> threeSum(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        for(int i=0; i<nums.size(); i++){
            int target = -nums[i];
            if(i>0 && nums[i]==nums[i-1]) continue;
            int start = i+1;
            int end = nums.size()-1;
            while(start<end){
                while(start>i+1 && nums[start]==nums[start-1]) start++;
                while(end<nums.size()-1 && nums[end]==nums[end+1]) end--;
                if(start>=end) break;
                if(nums[start]+nums[end] == target) {res.push_back({nums[i], nums[start], nums[end]});}
                if(nums[start]+nums[end]< target){
                    start++;
                }else{
                    end--;
                }
            }
        }
        return res;
    }
    

    };


  • 0

    @ahmad16 Please read the FAQ to format your code properly.


Log in to reply
 

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