File tree Expand file tree Collapse file tree 1 file changed +24
-24
lines changed Expand file tree Collapse file tree 1 file changed +24
-24
lines changed Original file line number Diff line number Diff line change 66
77class LongestIncreasingSubsequence {
88 func lengthOfLIS( _ nums: [ Int ] ) -> Int {
9- guard let first = nums. first else {
10- return 0
11- }
12-
13- var ends = [ first]
9+ var res = [ nums [ 0 ] ]
1410
1511 for i in 1 ..< nums. count {
16-
17- // find first greater ends number
18- var left = 0 , right = ends. count
19-
20- while left < right {
21- let mid = ( right - left) / 2 + left
22-
23- if ends [ mid] < nums [ i] {
24- left = mid + 1
25- } else {
26- right = mid
27- }
28- }
29-
30- if right >= ends. count {
31- ends. append ( nums [ i] )
12+ if res. last! < nums [ i] {
13+ res. append ( nums [ i] )
3214 } else {
33- ends [ right ] = nums [ i]
15+ res [ binarySearch ( res , nums [ i ] ) ] = nums [ i]
3416 }
3517 }
3618
37- return ends. count
19+ return res. count
20+ }
21+
22+ private func binarySearch( _ num: Int , _ res: [ Int ] ) -> Int {
23+ var l = 0 , r = res. count - 1
24+
25+ while l < r {
26+ let mid = ( r - l) / 2 + l
27+
28+ if res [ mid] == num {
29+ return mid
30+ } else if res [ mid] > num {
31+ r = mid
32+ } else {
33+ l = mid + 1
34+ }
35+ }
36+
37+ return l
3838 }
39- }
39+ }
You can’t perform that action at this time.
0 commit comments