μΊμ - νλ‘κ·Έλλ¨Έμ€(Swift)
μΊμ - νλ‘κ·Έλλ¨Έμ€(Swift)
λ¬Έμ μ€λͺ
https://school.programmers.co.kr/learn/courses/30/lessons/17680
νλ‘κ·Έλλ¨Έμ€
μ½λ μ€μ¬μ κ°λ°μ μ±μ©. μ€ν κΈ°λ°μ ν¬μ§μ λ§€μΉ. νλ‘κ·Έλλ¨Έμ€μ κ°λ°μ λ§μΆ€ν νλ‘νμ λ±λ‘νκ³ , λμ κΈ°μ κΆν©μ΄ μ λ§λ κΈ°μ λ€μ λ§€μΉ λ°μΌμΈμ.
programmers.co.kr
λμ νμ΄
μ²μμ LRUμκ³ λ¦¬μ¦μ΄ κ°μ₯ μ€λλ κ²μ κ΅μ²΄νλ μκ³ λ¦¬μ¦μ΄λΌκ³ μκ°νλλ° μ΄ μκ³ λ¦¬μ¦μ ν΅μ¬μ κΈ°μ‘΄μ μμ μλ κ°μ΄ λ μ°Έμ‘°νκ² λλ€λ©΄ κ°μ₯ μ΅μ μΈ μνλ‘ λ³κ²½νλ κ²μ΄ ν΅μ¬μ΄λ€.
μ¦ 3κ°μ μΊμ곡κ°μ΄ μμλ 1->2->3->2->4 κ° λ€μ΄μ¨λ€λ©΄ 2κ°λ€μ΄μ¬λ 1->2->3μ΄ μλ 1->3->2κ° λμ΄ 2κ° κ°μ₯ λ§μ§λ§μ λκ°κ² λλ€.
func solution(_ cacheSize:Int, _ cities:[String]) -> Int {
var caches: [String] = []
var time: Int = 0
if cacheSize == 0 {
return 5*(cities.count)
}
for city in cities {
if caches.contains(city.lowercased()) {
let idx = caches.firstIndex(of: city.lowercased())!
caches.remove(at: idx)
caches.append(city.lowercased())
time += 1
} else {
if caches.count == cacheSize {
caches.removeFirst()
}
caches.append(city.lowercased())
time += 5
}
}
return time
}
νΌλλ°±
λ°°μ΄μλ removeFirst(), removeLast()κ° μ‘΄μ¬νλ€.
λ°°μ΄μμ firstIndex()λ₯Ό μ¬μ©νκ³ μΆμλλ μΈμλ‘ ofλ₯Ό μ€μΌνλ€.