-
Notifications
You must be signed in to change notification settings - Fork 897
Expand file tree
/
Copy pathLongestIncreasingSubsequence.swift
More file actions
39 lines (32 loc) · 1001 Bytes
/
LongestIncreasingSubsequence.swift
File metadata and controls
39 lines (32 loc) · 1001 Bytes
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 {
var res = [nums[0]]
for i in 1..<nums.count {
if res.last! < nums[i] {
res.append(nums[i])
} else {
res[binarySearch(res, nums[i])] = nums[i]
}
}
return res.count
}
private func binarySearch(_ num: Int, _ res: [Int]) -> Int {
var l = 0, r = res.count - 1
while l < r {
let mid = (r - l) / 2 + l
if res[mid] == num {
return mid
} else if res[mid] > num {
r = mid
} else {
l = mid + 1
}
}
return l
}
}