Skip to content
This repository was archived by the owner on Aug 14, 2024. It is now read-only.

Latest commit

 

History

History
43 lines (33 loc) · 1.01 KB

259.md

File metadata and controls

43 lines (33 loc) · 1.01 KB

259. 3Sum Smaller

Description

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]

Thinking process

  1. Just a variant of the 3Sum closest problem
  2. Sort the array, pick an item, run the TwoSum subroutine on the rest of the array behind it
public int threeSumSmaller(int[] nums, int target) {
    Arrays.sort(nums);
    int count = 0;
    for(int i=0; i<nums.length; i++){
        int low = i + 1;
        int high = nums.length - 1;
        while(low < high){
            if(nums[i] + nums[low] + nums[high] < target){
                count += (high - low);
                low++;
            }else{
                high--;
            }
        }
    }
    return count;
}

Complexity

O(n2)