您的位置:首页 > 其它

LeetCode 3Sum Smaller

2016-03-11 14:15 309 查看
原题链接在这里: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]

题解:

3Sum类似. 计算和小于target的组合个数,重复的也要算. 若是nums[i] + nums[j] + nums[k] 符合要求,那么count += k-j, j++. 举例{-2, 0, 1, 3}. target = 4. {-2, 0, 3}符合要求, {-2, 0, 1}也符合要求,一次加上两个.

若是不符合要求说明等于或者大于target了, k--.

Time Complexity: O(n^2). Space: O(1).

AC Java:

public class Solution {
public int threeSumSmaller(int[] nums, int target) {
if(nums == null || nums.length == 0){
return 0;
}
Arrays.sort(nums);
int count = 0;
for(int i = 0; i<nums.length-2; i++){
int j = i+1;
int k = nums.length-1;
while(j<k){
if(nums[i] + nums[j] + nums[k] >= target){
k--;
}else{
count += k-j;
j++;
}
}
}
return count;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: