์บ์‹œ - ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค(Swift)

2022. 10. 11. 13:18ใ†ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค-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๋ฅผ ์ค˜์•ผํ•œ๋‹ค.