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.
[DP] Refactor the solution to Longest Increasing Subsequence
- Loading branch information
Showing
2 changed files
with
28 additions
and
12 deletions.
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 |
---|---|---|
@@ -1,23 +1,39 @@ | ||
/** | ||
* Question Link: https://leetcode.com/problems/longest-increasing-subsequence/ | ||
* Primary idea: Dynamic Programming, transition function is len[i] = max(len[i], len[j] + 1) | ||
* Time Complexity: O(n^2), Space Complexity: O(n) | ||
* Primary idea: Dynamic Programming, update the array which ends at current index using binary search | ||
* Time Complexity: O(nlogn), Space Complexity: O(n) | ||
*/ | ||
|
||
class LongestIncreasingSubsequence { | ||
func lengthOfLIS(nums: [Int]) -> Int { | ||
var length_global = 0 | ||
var length_current = [Int](count: nums.count, repeatedValue: 1) | ||
func lengthOfLIS(_ nums: [Int]) -> Int { | ||
guard let first = nums.first else { | ||
return 0 | ||
} | ||
|
||
var ends = [first] | ||
|
||
for i in 0..<nums.count { | ||
for j in 0..<i { | ||
if nums[i] > nums[j] { | ||
length_current[i] = max(length_current[i], length_current[j] + 1) | ||
for i in 1..<nums.count { | ||
|
||
// find first greater ends number | ||
var left = 0, right = ends.count | ||
|
||
while left < right { | ||
let mid = (right - left) / 2 + left | ||
|
||
if ends[mid] < nums[i] { | ||
left = mid + 1 | ||
} else { | ||
right = mid | ||
} | ||
} | ||
length_global = max(length_global, length_current[i]) | ||
|
||
if right >= ends.count { | ||
ends.append(nums[i]) | ||
} else { | ||
ends[right] = nums[i] | ||
} | ||
} | ||
|
||
return length_global | ||
return ends.count | ||
} | ||
} |
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