Skip to content

Commit af2958c

Browse files
committed
Two Sum - Less than or equal to target
1 parent c58cf03 commit af2958c

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

SwiftyLeetCode.playground/Contents.swift

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Leetcode solutions in Swift.
1+
// Not only Leetcode solutions in Swift.
22
// Some solutions are from:
33
// https://github.com/soapyigu/LeetCode_Swift
44

@@ -117,6 +117,39 @@ twoSumIII.add(number: 5)
117117
twoSumIII.find(value: 4)
118118
twoSumIII.find(value: 7)
119119

120+
/**
121+
* Two Sum - Less than or equal to target
122+
* http://www.lintcode.com/en/problem/two-sum-less-than-or-equal-to-target/
123+
*/
124+
125+
extension Solution {
126+
class func twoSum5(nums: [Int]?, _ target: Int) -> Int {
127+
guard let nums = nums, nums.count > 1 else { return 0 }
128+
129+
let sortedNums = nums.sorted()
130+
var count = 0
131+
var left = 0
132+
var right = nums.count - 1
133+
134+
while left < right {
135+
let value = sortedNums[left] + sortedNums[right]
136+
if(value > target) {
137+
right -= 1
138+
} else {
139+
count += right - left
140+
left += 1
141+
}
142+
}
143+
144+
return count
145+
}
146+
}
147+
148+
let twoSum5Nums = [2, 7, 11, 15]
149+
let twoSum5Target = 24
150+
151+
Solution.twoSum5(nums: twoSum5Nums, twoSum5Target)
152+
120153
/**
121154
* 217. Contains Duplicate
122155
* https://leetcode.com/problems/contains-duplicate/

0 commit comments

Comments
 (0)