259. 较小的三数之和
题目描述
给定一个长度为 n 的整数数组和一个目标值 target,寻找能够使条件 nums[i] + nums[j] + nums[k] < target 成立的三元组 i, j, k 个数(0 <= i < j < k < n)。
示例:
输入: nums = [-2,0,1,3], target = 2
输出: 2
解释: 因为一共有两个三元组满足累加和小于 2:
[-2,0,1]
[-2,0,3]
进阶:是否能在 O(n2) 的时间复杂度内解决?
解法
双指针解决。
Python3
class Solution: def threeSumSmaller(self, nums: List[int], target: int) -> int: def threeSumSmaller(nums, start, end, target): count = 0 while start < end: if nums[start] + nums[end] < target: count += (end - start) start += 1 else: end -= 1 return count nums.sort() n, count = len(nums), 0 for i in range(n - 2): count += threeSumSmaller(nums, i + 1, n - 1, target - nums[i]) return count
Java
class Solution { public int threeSumSmaller(int[] nums, int target) { Arrays.sort(nums); int n = nums.length; int count = 0; for (int i = 0; i < n - 2; ++i) { count += threeSumSmaller(nums, i + 1, n - 1, target - nums[i]); } return count; } private int threeSumSmaller(int[] nums, int start, int end, int target) { int count = 0; while (start < end) { if (nums[start] + nums[end] < target) { count += (end - start); ++start; } else { --end; } } return count; } }