Leetcode 259 Solution

This article provides solution to leetcode question 259 (3sum-smaller)

https://leetcode.com/problems/3sum-smaller

Solution

class Solution {
public:
    int threeSumSmaller(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());

        int total = 0;
        for (int i = 0; i < nums.size(); i++)
        {
            int sum = target - nums[i];
            int l = i + 1;
            int r = nums.size() - 1;

            while (l < r)
            {
                if (nums[l] + nums[r] < sum)
                {
                    total += r - l;
                    l++;
                }
                else
                    r--;
            }
        }

        return total;
    }
};