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?
解法1: O(N^2)
O(N^2)的解法和3Sum或者3Sum closest类似,但比较tricky的地方是,在用双指针left和right找到一个<target的数的时候,其实right 和left之间所有的数都满足要求(排序之后)。所以这个时候我们把right-left加入到res中,然后更新left即可。
|
|