Skip to content

Commit

Permalink
Add a solution to Two Sum Less Than K
Browse files Browse the repository at this point in the history
  • Loading branch information
soapyigu committed Jul 2, 2019
1 parent fb2b843 commit 6bb57bd
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
28 changes: 28 additions & 0 deletions Array/TwoSumLessThanK.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* Question Link: https://leetcode.com/problems/two-sum-less-than-k/
* Primary idea: Sort the arry and use two pointers to get the closest maximum value.
*
* Note: Directly using two points and update values correspondly to try to solve the
* problem with O(n) time complexity does not work -- it has too many edge cases.
*
* Time Complexity: O(n), Space Complexity: O(n)
*/

class TwoSumLessThanK {
func twoSumLessThanK(_ A: [Int], _ K: Int) -> Int {
let sortedA = A.sorted()
var left = 0, right = sortedA.count - 1
var closest = -1

while left < right {
if sortedA[left] + sortedA[right] < K {
closest = max(sortedA[left] + sortedA[right], closest)
left += 1
} else {
right -= 1
}
}

return closest
}
}
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
![Leetcode](./logo.png?style=centerme)

## Progress
[Problem Status](#problem-status) shows the latest progress to all 800+ questions. Currently we have 275 completed solutions. Note: questions with &hearts; mark means that you have to **Subscript to premium membership** of LeetCode to unlock them.
[Problem Status](#problem-status) shows the latest progress to all 800+ questions. Currently we have 276 completed solutions. Note: questions with &hearts; mark means that you have to **Subscript to premium membership** of LeetCode to unlock them.

## Contributors

Expand Down Expand Up @@ -58,6 +58,7 @@
[Remove Element](https://leetcode.com/problems/remove-element/)| [Swift](./Array/RemoveElement.swift)| Easy| O(n)| O(1)|
[Strobogrammatic Number](https://leetcode.com/problems/strobogrammatic-number/)| [Swift](./Array/StrobogrammaticNumber.swift)| Easy| O(n)| O(1)|
[Two Sum](https://leetcode.com/problems/two-sum/)| [Swift](./Array/TwoSum.swift)| Easy| O(n)| O(n)|
[Two Sum Less Than K](https://leetcode.com/problems/two-sum-less-than-k/)| [Swift](./Array/TwoSumLessThanK.swift)| Easy| O(nlogn)| O(n)|
[3Sum](https://leetcode.com/problems/3sum/)| [Swift](./Array/ThreeSum.swift)| Medium| O(n^2)| O(nC3)|
[3Sum Closest](https://leetcode.com/problems/3sum-closest/)| [Swift](./Array/ThreeSumClosest.swift)| Medium| O(n^2)| O(nC3)|
[4Sum](https://leetcode.com/problems/4sum/)| [Swift](./Array/FourSum.swift)| Medium| O(n^3)| O(nC4)|
Expand Down

0 comments on commit 6bb57bd

Please sign in to comment.