forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add a solution to Two Sum Less Than K
- Loading branch information
Showing
2 changed files
with
30 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters