[Hyun] Week 7 Solution Explanation #127
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
143. Reorder List
Complexities ๐
Explanation ๐
์ฒ์์๋ ํ๋์ ๋ฉ์๋๋ฅผ ํ์ฉํด์ ์ฌ๊ท๋ก ๋๋ฆด ์ ์์๊น ๊ณ ๋ฏผํ์ง๋ง ์์ง ์ ๋จธ๋ฆฌ๋ก๋ ๋ช ํํ๊ฒ ๊ตฌ์ํ์ง ๋ชปํด while๋ฌธ๊ณผ for๋ฌธ์ ์ด์ฉํ์ฌ ํ์ดํ์ต๋๋ค.
์ ๊ทธ๋ฆผ์ฒ๋ผ ๊ฐ ๋ ธ๋์
next
๋ฅผ ๋ฌํฝ์ด์ฒ๋ผ ์ฐ๊ฒฐ์ง์ด์ค์ผํ๊ธฐ ๋๋ฌธ์,head
๋ถํฐtail
๊น์ง๋ฅผ ๋ฐ๋ณตํ๋ฉฐ ๋ฆฌ์คํธ์ ๋ฃ์ด์ฃผ์์ต๋๋ค.๊ทธ ๋ค, ๋ฆฌ์คํธ์ ๋ค์ด๊ฐ ๊ฐ ๋ ธ๋๋ค์ index๋ก ์ ๊ทผํ์ฌ
next
์ ๊ฐ์ ์๋ง๊ฒ ์์ ํด์ฃผ์์ต๋๋ค.์ด๋ ๊ฒ
next
๋ฅผ ์ค์ ํ๋ค๋ณด๋ฉด ๋ง์ง๋ง์ ์๊ธฐ ์์ ์ ์ฐธ์กฐํ๊ฒ ๋๋ ๊ฒฝ์ฐ๊ฐ ๋ฐ์ํ๋๋ฐ, ์กฐ๊ฑด์์ ํตํด ์๊ธฐ ์์ ์ผ๋ก ํ ๋น์ด ๋ ๊ฒฝ์ฐ๋ฅผ ํ๋จํ์ฌnull
๋ก ์ค์ ํด์ฃผ์์ต๋๋ค.ํ์์ธ ๊ฒฝ์ฐ์๋ ๋ฐ๋ณต๋ฌธ์์ ๋ฐ๋ก ์ฒ๋ฆฌ๋์ง ์๊ธฐ ๋๋ฌธ์ ์ถ๊ฐ๋ก
next
๋ฅผnull
๋ก ์ค์ ํด์ฃผ๋ ์ฝ๋๋ฅผ ๋ฃ์์ต๋๋ค.19. Remove Nth Node From End of List
Complexities ๐
Explanation ๐
์ฒ์์๋ Space Complexity๊ฐ$O(c)$ (c = node์ ์)๋ก ๋์ํ๋ ์ฝ๋๋ก ๊ตฌํํ์ผ๋, $O(1)$ ๋ก ํ์ดํ ์ ์์์ต๋๋ค.
n
๋งํผ ๋จผ์ ์ด๋ํ ๋ ธ๋์, head๋ฅผ ๊ฐ๋ฆฌํค๋ ๋ ธ๋์ ํจ๊ป ํ๋์ฉnext
๋ฅผ ํตํด ๋ฐ๋ณตํจ์ผ๋ก์จ ๊ธฐ์กด์ ์ด๋ํ๋ ๋ ธ๋๊ฐ nil์ ๋ฐ๊ฒฌํ๊ฒ ๋ ๊ฒฝ์ฐ ๋์ค์ ๋ฐฉ๋ฌธํ๊ธฐ ์์ํ๋ ๋ ธ๋๋ ๋์์n
๋ฒ์งธ๋ฅผ ๊ฐ๋ฆฌํค๋ ๊ฒ์ ํ์ธํ์ต๋๋ค. ์ด๋ฅผ ํตํด235. Lowest Common Ancestor of a Binary Search Tree
Complexities ๐
Explanation ๐
์ฒ์์๋ ๋ถ๋ชจ์์๊ด๊ณ๋ก์๋ง ํ์ ํ์ผ๋, ๋์๊ฐ ์กฐ๋ถ๋ชจ ๊ทธ ์ด์์ ๊ด๊ณ๊ฐ ๋ ์ ์๋ค๋ ๊ฒ์ ๋ฏธ์ฒ ํ์ ํ์ง ๋ชปํ์์ต๋๋ค.
๊ทธ๋์ root ๋ ธ๋์ p, q๊ฐ ๋์ผํ๋ค๋ฉด ํด๋น ๋ ธ๋๋ฅผ ๋ฆฌํดํด์ฃผ๊ณ , ๊ทธ๊ฒ ์๋๋ผ๋ฉด root๋ ธ๋์ ์์๋ ธ๋๋ก ์ฌ๊ท๋ฅผ ๋๋ ธ์ต๋๋ค.๊ทธ ์ดํ left์ right๊ฐ ์ ๋ถ ๊ฐ์ด ์กด์ฌํ๋ค๋ฉด root๋ ธ๋๋ฅผ ๋ฆฌํดํ๊ณ , ํ ์ชฝ์ ์น์ฐ์ณ์ ธ์๋ค๋ฉด, ํด๋น ๊ฐ์ ๊ทธ๋๋ก ๋ฆฌํดํ๋ ์์ผ๋ก ๊ตฌํํ์ต๋๋ค.๋ง์นจ Valid BST๊ฐ ๊ธฐ์ค๋ ธ๋์ ์ผ์ชฝ ์ซ์๋ ๊ธฐ์ค ๋ ธ๋์ ์๋ณด๋ค ์๊ณ , ์ค๋ฅธ์ชฝ ๋ ธ๋๋ค์ ์ซ์๋ ๊ธฐ์ค ๋ ธ๋๋ณด๋ค ํฌ๋ค๋ ์ ์ ์ฐฉ์ํ์ฌ ๋ฌธ์ ํ์ด๋ฅผ ๋ณ๊ฒฝํ์ต๋๋ค.
102. Binary Tree Level Order Traversal
Complexities ๐
Explanation ๐
Swift๋ Queue๊ฐ ์์ด์ Linked-List๋ก ๊ตฌํํ์ต๋๋ค.(์ฌ์ค ํธ๋ฆฌ์ ๊ธธ์ด๊ฐ ๊ทธ๋ ๊ฒ ๊ธธ์ง ์์์ Array๋ฅผ ์ด์ฉํ ํ์ด๋ ์ข๊ธด ํฉ๋๋ค.)
Root๋ ธ๋์ ๊ฐ์์ layer๊ณ์ธต์ ๊ณ ๋ คํ์ฌ Queue์ ๋ ธ๋์ Intํ์ ์ layer๋ฅผ ํธ์ ๋ฐ ํ ํ๋ ๋ฐฉ์์ผ๋ก ๊ตฌํํ์ต๋๋ค.
98. Validate Binary Search Tree
Complexities ๐
Explanation ๐
์ฌ๊ท๋ฅผ ์ด์ฉํ์ฌ ํ์ดํ์ต๋๋ค. left๋ฅผ ์ฐ์ ๊ฒ์ฆํ ๋ค์, ์ค๋ฅธ์ชฝ์ ํ์ํ๊ณ , ์ถ์ ์์ํ ์ด์ ๋ ธ๋๋ฅผ ๋ณ๋๋ก ๊ตฌ์ฑํ์ฌ ์๋ก ๋น๊ตํ๋๋ก ๊ตฌํํ์ต๋๋ค.