3Sum Smaller

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]
Follow up:
Could you solve it in O(n2) runtime?

Show Company Tags
Show Tags
Show Similar Problems

小心这里是index triplets, 不是nums[i]数组元素的triplets, 所以3Sum那道题里面的跳过条件不用了

因为不关心每个index具体是什么,只关心个数,所以可以排序

public class Solution {
    public int threeSumSmaller(int[] nums, int target) {
        int res = 0;
        Arrays.sort(nums);
        for (int i=nums.length-1; i>=2; i--) {
            //if (i!=nums.length-1 && (nums[i]==nums[i+1])) continue;
            res += twoSum(nums, 0, i-1, target-nums[i]);
        }
        return res;
    }
    
    public int twoSum(int[] nums, int l, int r, int target) {
        int sum = 0;
        while (l < r) {
            if (nums[l]+nums[r] < target) {
                sum += r-l;
                l++;
            }
            else {
                r--;
            }
        }
        return sum;
    }
}

  

posted @ 2017-12-20 10:36  apanda009  阅读(141)  评论(0编辑  收藏  举报