原题网址:https://leetcode.com/problems/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?
方法一:暴力解法。
public class Solution {
public int threeSumSmaller(int[] nums, int target) {
int counts = 0;
for(int i=0; i<nums.length-2; i++) {
for(int j=i+1; j<nums.length-1; j++) {
for(int k=j+1; k<nums.length; k++) {
if (nums[i]+nums[j]+nums[k]<target) counts ++;
}
}
}
return counts;
}
}
方法二:使用TreeMap。
public class Solution {
public int threeSumSmaller(int[] nums, int target) {
if (nums == null || nums.length < 3) return 0;
int counts = 0;
TreeMap<Integer, Integer> treemap = new TreeMap<>();
treemap.put(nums[0], 1);
for(int i=1; i<nums.length-1; i++) {
for(int j=i+1; j<nums.length; j++) {
for(int count: treemap.headMap(target-nums[i]-nums[j]).values()) {
counts += count;
}
}
Integer count = treemap.get(nums[i]);
if (count == null) count = 1; else count ++;
treemap.put(nums[i], count);
}
return counts;
}
}
方法三:由于题目只要求统计结果,不需要范围原始的下标组合,因此完全可以对数组进行排序!一开始就是因为不敢排序,所以想不到这个方法。
思路:多个数值和问题都可以用类似的解法,这道题的特点在于条件隐含,第二个数从左边开始,第三个数从右边开始,当三数值和小于target,隐含的条件是第二个数和第三个之间的任何一对数字都能够符合条件。
public class Solution {
public int threeSumSmaller(int[] nums, int target) {
Arrays.sort(nums);
int count = 0;
for(int i=0; i<nums.length-2; i++) {
int j=i+1, k=nums.length-1;
while (j<k) {
if (nums[i]+nums[j]+nums[k] < target) {
count += k-j;
j ++;
} else {
k --;
}
}
}
return count;
}
}