LeetCode刷题实战259:较小的三数之和
共 3656字,需浏览 8分钟
·
2021-05-10 14:31
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.
示例
示例:
输入: nums = [-2,0,1,3], target = 2
输出: 2
解释: 因为一共有两个三元组满足累加和小于 2:
[-2,0,1]
[-2,0,3]
进阶:是否能在 O(n2) 的时间复杂度内解决?
解题
public class Solution {
public int threeSumSmaller(int[] nums, int target) {
// 先将数组排序
Arrays.sort(nums);
int cnt = 0;
for(int i = 0; i < nums.length - 2; i++){
int left = i + 1, right = nums.length - 1;
while(left < right){
int sum = nums[i] + nums[left] + nums[right];
// 如果三个数的和大于等于目标数,那将尾指针向左移
if(sum >= target){
right--;
// 如果三个数的和小于目标数,那将头指针向右移
} else {
// right - left个组合都是小于目标数的
cnt += right - left;
left++;
}
}
}
return cnt;
}
}