-
Notifications
You must be signed in to change notification settings - Fork 0
Closed
Description
๐ฌย ๋ฌธ์
https://app.codility.com/programmers/lessons/4-counting_elements/frog_river_one/
๐ฌย Idea
- ์ฒ์์๋ X ํฌ๊ธฐ๋ฅผ ๊ฐ์ง ๋ฐฐ์ด์ false๋ก ๋ชจ๋ ์ด๊ธฐํํ์ฌ ์์ฑํ ๋ค, ๋ฐ๋ณต๋ฌธ์ ๋๋ฉฐ ํด๋น ์ธ๋ฑ์ค์ ๊ฐ์ true๋ก ๋ฐ๊พผ ํ ์กฐ๊ฑด๋ฌธ์ ํตํด ํด๋น ๋ฐฐ์ด์ด ๋ชจ๋ true์ธ์ง ๊ฒ์ฌํด์ฃผ๋ ์์ ์ ๊ฑฐ์ณค์๋ค. ๊ทธ๋ฌ๋ ์ด๋ ๊ฒ ํ๋ ๋ฐ๋ณต๋ฌธ ์์ O(N)์ ์๊ฐ๋ณต์ก๋๋ฅผ ๊ฐ์ง๋ ์์ ์ด ๋ค์ด์์ด ์๊ฐ ์ด๊ณผ๊ฐ ๋ฐ์ํ๋ค.
- ๋ฐ๋ผ์ ํ์ด ์ ๊ทผ๋ฒ์ ์กฐ๊ธ ๋ณ๊ฒฝํ์ฌ Set ์๋ฃ๊ตฌ์กฐ๋ฅผ ์ฌ์ฉํ๋ค. ๋ฌธ์ ์ ์กฐ๊ฑด์์ ๋ฐฐ์ด์ ์์์ ๊ฐ์ ๋ฌด์กฐ๊ฑด X + 1 ์ด๋ด์ ์๋ผ ํ์ผ๋ฏ๋ก Set์ ์ฐจ๋ก๋ก ์์๋ฅผ ์ง์ด๋ฃ์ ํ ํด๋น ๋ฐฐ์ด์ count๊ฐ X์ ๋์ผํด์ง ๋๋ฅผ ๊ฒ์ฌํ์ฌ ํด๋น ์๊ฐ์ ๋ฆฌํดํด์ฃผ์๋ค.
- count ๋น๊ต๋ O(1)์ ์๊ฐ๋ณต์ก๋๋ฅผ ๊ฐ์ง๋ฏ๋ก ํจ์ฌ ํจ์จ์ ์ด๋ค.
๐ฌย ํ์ด
public func solution(X : Int, A : inout [Int]) -> Int {
var leafArr: Set<Int> = []
for (idx, i) in A.enumerated() {
leafArr.insert(i)
if leafArr.count == X { return idx }
}
return -1
}
์์์๊ฐ
: 15๋ถ
์๊ฐ ๋ณต์ก๋
: O(N)
ํ๊ฐํ
: https://app.codility.com/demo/results/trainingXMSU6T-TQB/