알고리즘
[Swift] 프로그래머스 - 카카오 캐시
고고
2022. 2. 28. 21:30
문제: https://programmers.co.kr/learn/courses/30/lessons/17680
코딩테스트 연습 - [1차] 캐시
3 ["Jeju", "Pangyo", "Seoul", "NewYork", "LA", "Jeju", "Pangyo", "Seoul", "NewYork", "LA"] 50 3 ["Jeju", "Pangyo", "Seoul", "Jeju", "Pangyo", "Seoul", "Jeju", "Pangyo", "Seoul"] 21 2 ["Jeju", "Pangyo", "Seoul", "NewYork", "LA", "SanFrancisco", "Seoul", "Ro
programmers.co.kr
queue의 왼쪽은 가장 사용되지 않은 것들, 오른쪽은 최근에 사용된 것들을 유지했습니다.
0일 때에는 queue에 관계없이 cache miss처리를 하였습니다.
import Foundation
func solution(_ cacheSize:Int, _ cities:[String]) -> Int {
var result = 0
var queue = [String]()
for city in cities {
let city = city.lowercased()
if queue.contains(city) { // hit
result += 1
queue.remove(at: queue.firstIndex(of: city)!)
} else { // miss
result += 5
if cacheSize == 0 {
continue
}
if queue.count >= cacheSize {
queue.removeFirst()
}
}
queue.append(city)
}
return result
}