3Sum Smaller
Problem:
题意又理解错了,人家并没有要求去重复。If found current sum < target, then from l to r all sums are smaller than target. Similar to Valid Triangle Number.
Solution:
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]Analysis:
题意又理解错了,人家并没有要求去重复。If found current sum < target, then from l to r all sums are smaller than target. Similar to Valid Triangle Number.
Solution:
class Solution { public int threeSumSmaller(int[] nums, int target) { int res = 0; if (nums == null || nums.length == 0) return res; Arrays.sort(nums); for (int i = 0; i < nums.length - 2; i++) { int l = i + 1, r = nums.length - 1; while (l < r) { int sum = nums[l] + nums[r] + nums[i]; if (sum < target) { res += (r - l); l++; } else { r--; } } } return res; } }
评论
发表评论