yokostan / Leetcode-Solutions

Doing exercise on Leetcode. Carry on!
0 stars 3 forks source link

Leetcode #259. 3Sum Smaller #236

Open yokostan opened 5 years ago

yokostan commented 5 years ago

Two pointers and count += a range of numbers:

class Solution {
    public int threeSumSmaller(int[] nums, int target) {
        int count = 0;
        if (nums == null || nums.length == 0) return count;

        Arrays.sort(nums);

        for (int i = 0; i <= nums.length - 3; i++) {
            int start = i + 1;
            int end = nums.length - 1;
            while (start < end) {
                    if (nums[end] + nums[start] + nums[i] < target) {
                        count += end - start;
                        start++;
                    }
                    else {
                        end--;
                    }
                }
        }

        return count;
    }
}