跳到主要内容

3Sum Smaller

描述

Given an array of n integers nums and an integer 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.

Follow up: Could you solve it in O(n2n^2) runtime?

Example 1:

Input: nums = [-2,0,1,3], target = 2

Output: 2

Explanation: Because there are two triplets which sums are less than 2:

[-2,0,1]

[-2,0,3]

Example 2:

Input: nums = [], target = 0

Output: 0

Example 3:

Input: nums = [0], target = 0

Output: 0

Constraints:

  • n == nums.length
  • 0 <= n <= 300
  • -100 <= nums[i] <= 100
  • -100 <= target <= 100

分析

先排序,然后双指针左右夹逼,复杂度 O(n2)O(n^2)

代码

# 3Sum Smaller
# 先排序,然后双指针左右夹逼
# Time Complexity: O(n^2)
# Space Complexity: O(1)
class Solution:
def threeSumSmaller(self, nums: List[int], target: int) -> int:
nums.sort()
count = 0
for i in range(len(nums)-2):
count += self.twoSumSmaller(nums, i, target - nums[i])
return count

def twoSumSmaller(self, nums: List[int], i: int, target: int) -> int:
count = 0
left, right = i + 1, len(nums) - 1
while left < right:
if nums[left] + nums[right] < target:
count += right - left
left += 1
else:
right -= 1
return count

相关题目