clueless coding // TODO: be smarter

LeetCode 3Sum: C++ Solution



TL;DR Code Solution


vector<vector<int>> threeSum(vector<int>& nums) {
    sort(nums.begin(), nums.end());
    vector<vector<int>> result;

    for (int i = 0; i < (int)nums.size() - 2; i++) {
        int pin = nums[i];
        int left = i + 1;
        int right = (int)nums.size() - 1;
        while (left < right) {
            if (pin + nums[left] + nums[right] == 0) {
                int numLeft = nums[left];
                int numRight = nums[right];
                vector<int> current = {pin, nums[left], nums[right]};
                result.push_back(current);

                while (left < right && nums[left] == numLeft)
                    left++;

                while (left < right && nums[right] == numRight)
                    right--;
            }
            else if (pin + nums[left] + nums[right] < 0) {
                left++;
            }
            else {
                right--;
            }
        }

        while (i + 1 < nums.size() && nums[i + 1] == nums[i])
            i++;

    }

    return result;


}