ํฌ๋ ์ธ ์ธํ๋ฝ๊ธฐ - ํ๋ก๊ทธ๋๋จธ์ค(Swift)
2022. 10. 4. 09:50ใํ๋ก๊ทธ๋๋จธ์ค-Swift
ํฌ๋ ์ธ ์ธํ๋ฝ๊ธฐ - ํ๋ก๊ทธ๋๋จธ์ค(Swift)
๋ฌธ์ ์ค๋ช
https://school.programmers.co.kr/learn/courses/30/lessons/64061?language=swift
๋์ ํ์ด
๋ฐ์์๋ถํฐ ํ์ํ๊ธฐ ์ํด stride๋ฉ์๋๋ฅผ ์ฌ์ฉํ๋ค
๋ด ํ์ด์์๋ ๋จผ์ ๊ฒฐ๊ณผ๋ฐฐ์ด์ ๋ฃ๊ณ ์ค๋ณต๋๋ฉด ์ ๊ฑฐํด์ ํด๊ฒฐํ๋ค
import Foundation
func solution(_ board:[[Int]], _ moves:[Int]) -> Int {
var results:[Int] = []
var array = board
var deleteObj = 0
for num in moves {
var maxIdx = 0
var selectedVal = 0
for i in stride(from: board.count-1, through: 0, by: -1) {
if array[i][num-1] > 0 {
maxIdx = i
selectedVal = array[i][num-1]
}
}
array[maxIdx][num-1] = 0
if selectedVal > 0 {
results.append(selectedVal)
}
if results.count > 1 {
if results[results.count-1] == results[results.count-2] {
deleteObj += 2
results.removeLast()
results.removeLast()
}
}
}
return deleteObj
}
๋ค๋ฅธ ์ฌ๋์ ํ์ด
๊ฒฐ๊ณผ๋ฐฐ์ด์ ๊ฐ์ ๋ฃ๊ณ ๋ก์ง์ ์ฒ๋ฆฌํ๋ ๋ด ํ์ด์ ๋ฌ๋ฆฌ ๋ฃ๊ธฐ ์ ์ ์ฒ๋ฆฌํจ์ผ๋ก์จ ๋ ๊ฐ๊ฒฐํ๊ฒ ์งค ์ ์๊ฒ ๋์๋ค.
๋ฐฐ์ด์ ์ฌ์ฉํ ๋ lastํ๋กํผํฐ๋ฅผ ์ด์ฉํจ์ผ๋ก์จ ๋งจ ๋ง์ง๋ง ์ธ๋ฑ์ค์ ์ฝ๊ฒ ์ ๊ทผ์ด ๊ฐ๋ฅํ๋ค.
๊ทธ๋ฆฌ๊ณ ๋ฐฐ์ด์ ์์์๋ถํฐ ํ์ํ๋ ๊ฐ์ด ์์ผ๋ฉด breakํจ์ผ๋ก์จ ์๊ฐ์ด ๋ ๊ฑธ๋ฆฌ๊ธฐ ๋๋ฌธ์ ๋ ์ข์ ์ฝ๋์ธ ๊ฒ ๊ฐ๋ค.
import Foundation
func solution(_ board:[[Int]], _ moves:[Int]) -> Int {
var results:[Int] = []
var array = board
var deleteObj = 0
for num in moves {
for i in 0..<board.count {
if array[i][num-1] > 0 {
if results.last == array[i][num-1] {
deleteObj += 2
results.removeLast()
} else {
results.append(array[i][num-1])
}
array[i][num-1] = 0
break
}
}
}
return deleteObj
}
'ํ๋ก๊ทธ๋๋จธ์ค-Swift' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
ํ๋ก๊ทธ๋๋จธ์ค - ์ ๊ณ ๊ฒฐ๊ณผ๋ฐ๊ธฐ(Swift) (0) | 2022.10.05 |
---|---|
์ฑ๊ฒฉ์ ํ ๊ฒ์ฌํ๊ธฐ - ํ๋ก๊ทธ๋๋จธ์ค(Swift) (1) | 2022.10.05 |
ํคํจ๋ ๋๋ฅด๊ธฐ - ํ๋ก๊ทธ๋๋จธ์ค(Swift) (1) | 2022.10.03 |
ํ๋ก๊ทธ๋๋จธ์ค - ์ฒด์ก๋ณต(Swift) (0) | 2022.10.02 |
๋ก๋์ ์ต๊ณ ์์์ ์ต์ ์์ - ํ๋ก๊ทธ๋๋จธ์ค(Swift) (0) | 2022.10.02 |