Sunday, December 27, 2015

3Sum Smaller -- Leetcode

Question:
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]

Answer:
Time: O(n^2), sort method.
public int threeSumSmaller(int[] nums, int target) {
        Arrays.sort(nums);
        int count = 0;
     
        for(int i=0; i < nums.length; ++i){
            int j = i+1;
            int k = nums.length - 1;

            while(j < k){
                if(nums[i] + nums[j] + nums[k] < target){
                    count += (k-j);
                    j++;
                }else if(nums[i] + nums[j] + nums[k] >= target){
                    k--;
                }
            }
        }
        return count;
}

No comments:

Post a Comment