Leetcode: 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具体是什么,只关心个数,所以可以排序

 1 public class Solution {
 2     public int threeSumSmaller(int[] nums, int target) {
 3         int res = 0;
 4         Arrays.sort(nums);
 5         for (int i=nums.length-1; i>=2; i--) {
 6             //if (i!=nums.length-1 && (nums[i]==nums[i+1])) continue;
 7             res += twoSum(nums, 0, i-1, target-nums[i]);
 8         }
 9         return res;
10     }
11     
12     public int twoSum(int[] nums, int l, int r, int target) {
13         int sum = 0;
14         while (l < r) {
15             if (nums[l]+nums[r] < target) {
16                 sum += r-l;
17                 l++;
18             }
19             else {
20                 r--;
21             }
22         }
23         return sum;
24     }
25 }
原文地址:https://www.cnblogs.com/EdwardLiu/p/5068727.html