259. 3Sum Smaller
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
.
Example:
Follow up: Could you solve it in O(n2) runtime?
Thoughts
对给定数组统计满足和小于target的三元组个数。2 Sum。排序并遍历i,在[0, i - 1]范围内维持首尾双指针l和r,[l, r]看作当前问题范围,当它俩加起来< target - nums[i]时说明[l+1, r]所有数都能和nums[l]拼成合法对,res += r - l,跳过l;否则说明[l, r - 1]中任何数都不能和nums[r]组成合法对,r--。
Code
Analysis
时间复杂度O(N^2).
Last updated
Was this helpful?