★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-hbftfxho-ma.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
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
.git
For example, given nums = [-2, 0, 1, 3]
, and target = 2.github
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?微信
給定n個整數nums和一個目標的數組,找出知足條件nums[i]+nums[j]+nums[k]<目標的索引三元組i、j、k的個數,其中0<=i<j<k<n。less
例如,給定nums=[-2,0,1,3]和target=2。spa
返回2。由於有兩個三元組的和小於2:code
[-2, 0, 1] [-2, 0, 3]
進階:htm
你能在O(n2)運行時解決它嗎?blog
1 class Solution { 2 func threeSumSmaller(_ nums:[Int],_ target:Int) -> Int{ 3 var nums = nums 4 if nums.count < 3 {return 0} 5 var res:Int = 0 6 var n:Int = nums.count 7 nums = nums.sorted(by:<) 8 for i in 0..<(n - 2) 9 { 10 var left:Int = i + 1 11 var right:Int = n - 1 12 while (left < right) 13 { 14 if nums[i] + nums[left] + nums[right] < target 15 { 16 res += right - left 17 left += 1 18 } 19 else 20 { 21 right -= 1 22 } 23 } 24 } 25 return res 26 } 27 }