Leetcode 259. 3Sum Smaller

 class Solution(object):
def threeSumSmaller(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
n = len(nums)
ans = 0 for k in range(n):
i, j = k+1, n-1
while i<j:
sum3 = nums[k] + nums[i] + nums[j]
if sum3 < target:
ans += j - i
i += 1
else:
j -= 1
return ans

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?

思路: 相遇型two pointers。注意L17, 这一句的意思是,如果 nums[k] + nums[i] + nums[j] < target,那么i和j之间的所有nums[p]+nums[k]+nums[i]也都满足条件。

 
 
上一篇:前端基础(CSS)


下一篇:如何处理alert、confirm、prompt对话框