File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
longest-increasing-subsequence Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ // O(nlogn) time / O(n) space
3
+ func lengthOfLIS( _ nums: [ Int ] ) -> Int {
4
+ var piles : [ Int ] = [ ]
5
+ // Patience(1์ธ ์นด๋๋์ด) sort ์ด์ฉ
6
+ for num in nums {
7
+ let leftInsertion = binarySearch ( piles: piles, target: num)
8
+
9
+ // piles[k] >= x์ธ pile์ด ์์ ๋๋ง append(๊ธธ์ด ์ฆ๊ฐ)
10
+ if leftInsertion == piles. count {
11
+ piles. append ( num)
12
+ } else {
13
+ //๊ฐ์ฅ ์ผ์ชฝ์ piles[k] >= x ์์น์ ๊ต์ฒด
14
+ piles [ leftInsertion] = num
15
+ }
16
+
17
+ }
18
+
19
+ // piles[k] = ๊ธธ์ด (k+1) ์ฆ๊ฐ์์ด์ด ๊ฐ์ง ์ ์๋ '๋๊ฐ์ ์ต์์น'
20
+ // sort ๋ก์ง์ piles.count๊ฐ ์ต๋ํ ๊ธธ๊ฒ ๋ง๋ค์๊ธฐ ๋๋ฌธ์ piles.count๋ ๊ฐ์ฅ ๊ธด ๊ธธ์ด๊ฐ ๋จ
21
+ return piles. count
22
+ }
23
+
24
+ func binarySearch( piles: [ Int ] , target: Int ) -> Int {
25
+ var left = 0
26
+
27
+ //target์ ์ฝ์
์์น๊ณ ๋งจ ๋์ ๋ง๋ถ์ผ์๋ ์์ด์ nums.count - 1 ์ด ์๋
28
+ var right = piles. count
29
+
30
+ while left < right {
31
+ let mid = left + ( right - left) / 2
32
+ if target > piles [ mid] {
33
+ left = mid + 1
34
+ } else {
35
+ //๋งจ ์ผ์ชฝ ๊ฑฐ๋ฅผ ์ฐพ์์ผ ํจ์ผ๋ก ๋ค์ ์ชผ๊ฐ๊ฐ๋ฉด์ ๋งจ ์ผ์ชฝ ๊ฑฐ๋ฅผ ์ฐพ๋๋ค. ๋งจ ์ผ์ชฝ ๊ฑฐ์ ๋ฃ์ด์ผ ๊ธธ์ด(k) ์ฆ๊ฐ์์ด์ ๋๊ฐ์ด ๊ฐ์ฅ ์๊ฒ ๋๋ค. ์ด๋์ผ ์ต๋ํ ๋ค์ ๊ณ์ ๋ ์ด์ด๋ถ์ฌ์ ์ต๋ํ ๊ธธ๊ฒ piles๋ฅผ ๋ง๋ค ์ ์์.
36
+ right = mid
37
+ }
38
+ }
39
+ return left
40
+ }
41
+ }
You canโt perform that action at this time.
0 commit comments