[LintCode] 3Sum Smaller

linspiration發表於2019-01-19

Problem

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.

Example

Given nums = [-2,0,1,3], target = 2, return 2.

Explanation:

Because there are two triplets which sums are less than 2:
[-2, 0, 1]
[-2, 0, 3]

Challenge

Could you solve it in O(n2) runtime?

Solution

public class Solution {
    /**
     * @param nums:  an array of n integers
     * @param target: a target
     * @return: the number of index triplets satisfy the condition nums[i] + nums[j] + nums[k] < target
     */
    public int threeSumSmaller(int[] nums, int target) {
        // Write your code here
        if (nums.length < 3) return 0;
        Arrays.sort(nums);
        if (nums[0] >= target) return 0;
        int count = 0;
        for (int i = 0; i < nums.length-2; i++) {
            int start = i+1, end = nums.length-1;
            int sum = target - nums[i];
            while (start < end) {
                if (nums[start] + nums[end] < sum) {
                    count += end-start;
                    start++;
                } else {
                    end--;
                }
            }
        }
        return count;
    }
}

相關文章