forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LongestIncreasingSubsequence.swift
39 lines (31 loc) · 1.05 KB
/
LongestIncreasingSubsequence.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* Question Link: https://leetcode.com/problems/longest-increasing-subsequence/
* 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 {
guard let first = nums.first else {
return 0
}
var ends = [first]
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
}
}
if right >= ends.count {
ends.append(nums[i])
} else {
ends[right] = nums[i]
}
}
return ends.count
}
}