259. 3Sum Smaller

2018-05-30  本文已影响0人  Nancyberry

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.

Example:

Input: nums = [-2,0,1,3], and target = 2
Output: 2
Explanation: 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?

Solution

Two-pointer, O(n ^ 2), S(1)

虽然nums中可能会有duplicates,但这道题求的是index triplets,所以不需要考虑重复值情况。所以还是挺简单的,用Two-pointer即可解决。注意计算count时需要加k - j而非1,因为所有(j, [j + 1, k])形成的组合都满足条件。

class Solution {
    public int threeSumSmaller(int[] nums, int target) {
        if (nums == null || nums.length < 3) {
            return 0;
        }
        
        Arrays.sort(nums);
        int count = 0;
        int n = nums.length;
        
        for (int i = 0; i < n - 2; ++i) {
            int j = i + 1;
            int k = n - 1;
            
            while (j < k) {
                int sum = nums[i] + nums[j] + nums[k];  // overflow?
                if (sum < target) {
                    count += k - j;     // combinations of j and [j + 1, k]
                    ++j;
                } else {
                    --k;
                }
            }
        }
        
        return count;
    }
}
上一篇下一篇

猜你喜欢

热点阅读