美文网首页
259. 3Sum Smaller

259. 3Sum Smaller

作者: Nancyberry | 来源:发表于2018-05-30 13:14 被阅读0次

    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;
        }
    }
    

    相关文章

      网友评论

          本文标题:259. 3Sum Smaller

          本文链接:https://www.haomeiwen.com/subject/gsvtsftx.html