My C++ solution - easy to understand!


  • 1
    E
    class Solution {
    public:
        int threeSumSmaller(vector<int>& nums, int target) {
            if(nums.size() < 3) {
                return 0;
            }
            sort(nums.begin(), nums.end());
            int count = 0;
            for(int i = 0 ; i < nums.size() - 1 ; ++i) {
                int j = i + 1;
                int k = nums.size() - 1;
                while(j < k) {
                    if(nums[i] + nums[j] + nums[k] < target) {
                        count = count + k - j;
                        ++j;
                    }
                    else {
                        --k;
                    }
                }
            }
            return count;
        }
    };

Log in to reply
 

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