๋ฌธ์ ์ค๋ช
๋ฐฐ์ด array์ i๋ฒ์งธ ์ซ์๋ถํฐ j๋ฒ์งธ ์ซ์๊น์ง ์๋ฅด๊ณ ์ ๋ ฌํ์ ๋, k๋ฒ์งธ์ ์๋ ์๋ฅผ ๊ตฌํ๋ ค ํฉ๋๋ค.
์๋ฅผ ๋ค์ด array๊ฐ [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3์ด๋ผ๋ฉด
- array์ 2๋ฒ์งธ๋ถํฐ 5๋ฒ์งธ๊น์ง ์๋ฅด๋ฉด [5, 2, 6, 3]์ ๋๋ค.
- 1์์ ๋์จ ๋ฐฐ์ด์ ์ ๋ ฌํ๋ฉด [2, 3, 5, 6]์ ๋๋ค.
- 2์์ ๋์จ ๋ฐฐ์ด์ 3๋ฒ์งธ ์ซ์๋ 5์ ๋๋ค.
๋ฐฐ์ด array, [i, j, k]๋ฅผ ์์๋ก ๊ฐ์ง 2์ฐจ์ ๋ฐฐ์ด commands๊ฐ ๋งค๊ฐ๋ณ์๋ก ์ฃผ์ด์ง ๋, commands์ ๋ชจ๋ ์์์ ๋ํด ์์ ์ค๋ช ํ ์ฐ์ฐ์ ์ ์ฉํ์ ๋ ๋์จ ๊ฒฐ๊ณผ๋ฅผ ๋ฐฐ์ด์ ๋ด์ return ํ๋๋ก solution ํจ์๋ฅผ ์์ฑํด์ฃผ์ธ์.
์ ํ ์กฐ๊ฑด
- array์ ๊ธธ์ด๋ 1 ์ด์ 100 ์ดํ์ ๋๋ค.
- array์ ๊ฐ ์์๋ 1 ์ด์ 100 ์ดํ์ ๋๋ค.
- commands์ ๊ธธ์ด๋ 1 ์ด์ 50 ์ดํ์ ๋๋ค.
- commands์ ๊ฐ ์์๋ ๊ธธ์ด๊ฐ 3์ ๋๋ค.
์ ์ถ๋ ฅ ์
array | commands | return |
[1, 5, 2, 6, 3, 7, 4] | [[2, 5, 3], [4, 4, 1], [1, 7, 3]] | [5, 6, 3] |
๋ด ๋ฌธ์ ํ์ด
func solution(_ array:[Int], _ commands:[[Int]]) -> [Int] {
var result = [Int]()
for i in 0..<commands.count {
var temp = [Int]()
for j in (commands[i][0]-1)...(commands[i][1]-1) {
temp.append(array[j])
}
temp = temp.sorted()
result.append(temp[commands[i][2]-1])
}
return result
}
- for๋ฌธ ์์์ ํ ํ๋ง๋ค temp ๋ฐฐ์ด์ ๋ง๋ค์ด ์ ๋ ฌ, k๋ฒ์งธ ์๋ฅผ result์ ์ถ๊ฐํด์ฃผ์๋ค.
์ธ์์ ์ธ ํ์ด
import Foundation
func solution(_ array:[Int], _ commands:[[Int]]) -> [Int] {
return commands.map({(key) in
return array[(key[0]-1)...(key[1]-1)].sorted()[key[2]-1]
})
}
- map์ ์ด์ฉํ์ฌ ๋ฐ๋ก return๋ฌธ์์ ๋ฐฐ์ด์ ์์ฑ, ์ ๋ ฌ, k๋ฒ์งธ ์ ๊ตฌํ๊ธฐ ๊น์ง ํ ๋ฒ์ ํด์ฃผ์๋ค.
๐ก ํผ๋๋ฐฑ
- ์ด๋ ํ์ด์๋ map์ ์ ์ ํ ์ฌ์ฉํ๋ฉด ํฐ ํจ๊ณผ๋ฅผ ๋ณผ ์ ์๋ ๋ฏ ํ๋ค,,
- ์ธ์์ ์ธ ํ์ด๋ ์ดํด๋ ๊ฐ์ง๋ง ์์ง ์ ๋ ๊ฒ๊น์ง map์ ์ฌ์ฉํ๊ธฐ๋ ์ด๋ ค์์ ์ฐ์ต์ด ํ์ํ ๋ฏ ํ๋ค.ใ
๋ฌธ์
'3๏ธโฃ Swift > Problem Solving' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Swift Algorithm] N๊ฐ์ ์ต์๊ณต๋ฐฐ์ Programmers(Lv.2) (1) | 2021.06.18 |
---|---|
[Swift Algorithm] ๋ชจ์๊ณ ์ฌ Programmers(Lv.1) (0) | 2021.06.18 |
[Swift Algorithm] ์์ ๋ง๋ค๊ธฐ Programmers(Lv.1) (0) | 2021.06.18 |
[Swift Algorithm] ๋ก๋์ ์ต๊ณ ์์์ ์ต์ ์์ Programmers(Lv.1) (0) | 2021.06.18 |
[Swift Algorithm] ์ฒด์ก๋ณต Programmers(Lv.1) (0) | 2021.06.18 |
๋๊ธ