3 Sum Smaller

Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target.

For example, given nums = [-2, 0, 1, 3], and target = 2.

Return 2. Because there are two triplets which sums are less than 2:

[-2, 0, 1]
[-2, 0, 3]
Follow up:
Could you solve it in O(n2) runtime?

Keep each two sum in the array, and use one loop to find sum which is smaller than target.

for i from 0 -> n - 1
    for j from i + 1 -> n
        map -> a[i] + a[j]

for map from 0 -> n
    for k from 0 -> n
        if map + k < target && k is not in map
            counter ++

Sort, Two pointer This is O(n^3), not efficiency.

    public int threeSumSmaller(int[] nums, int target) {
        if(nums.length < 3) return 0;
        Arrays.sort(nums);
        int counter = 0;
        for(int i = 0 ; i < nums.length - 2; i++){
            int b = i + 1, e = i + 2;
            while(b < nums.length - 1){
                if(e < nums.length && nums[i] + nums[b] + nums[e] < target){
                    e ++;
                    counter ++;
                    continue;
                }
                e = ++ b + 1;
            }
        }
        return counter;
    }

results matching ""

    No results matching ""