Focus On Develop ๐ŸคŸ๐ŸคŸ

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] K๋ฒˆ์งธ์ˆ˜ ๋ณธ๋ฌธ

iOS [Swift]/์•Œ๊ณ ๋ฆฌ์ฆ˜

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] K๋ฒˆ์งธ์ˆ˜

๋ˆ„๋ฆฌ๋‹ฌ์ดํ‹€ 2020. 12. 16. 14:18

<๋ฌธ์ œ>


<์ „๋žต์งœ๊ธฐ>

๋ฌธ์ œ์—์„œ ํ•˜๋ผ๋Š” ๋Œ€๋กœ๋งŒ ํ•˜๋ฉด ๋˜๋Š”..? ๋ฌธ์ œ ๊ฐ™๋‹ค. ํฌ๊ฒŒ ์ƒ๊ฐํ•ด์•ผ ํ•  ๋ถ€๋ถ„์€ ์—†์„ ๊ฒƒ ๊ฐ™์•˜๊ณ , ํ•œ๊ฐ€์ง€ ์ฃผ์˜ํ•ด์•ผ ํ•  ๋ถ€๋ถ„์€ commands์—์„œ ๊ฐ ์š”์†Œ(๋ฐฐ์—ด)์˜ ๊ฐ’๋“ค์€ "n๋ฒˆ์งธ" ์ด์ง€ ์ธ๋ฑ์Šค๊ฐ€ "n"์ž„์„ ๋‚˜ํƒ€๋‚ด๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ฏ€๋กœ, Out Of Index Error๋ฅผ ํ”ผํ•˜๊ธฐ ์œ„ํ•ด commands์˜ ๊ฐ ์š”์†Œ๋“ค์€ ์ธ๋ฑ์Šค๋กœ ํ™œ์šฉํ•˜๊ธฐ ์œ„ํ•ด ๋ชจ๋‘ -1์„ ์ฒ˜๋ฆฌํ•œ ํ›„์— ์‚ฌ์šฉ ํ•ด์•ผ ํ•œ๋‹ค๋Š” ์ ์ด๋‹ค.

 

<์ฝ”๋“œ>

import Foundation

func solution(_ array:[Int], _ commands:[[Int]]) -> [Int] {
    var result: [Int] = []
    for command in commands {
        var orderArray = array[command[0]-1...command[1]-1].sorted()
        result.append(orderArray[command[2]-1])
    }
    return result
}

 

<Lesson Learned>

์˜ค๋žœ๋งŒ์— ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ๋‹ค์‹œ ์‹œ์ž‘ํ•˜๋Š” ์ (๋Œ€ํ•™์ƒ๋•Œ ์ดํ›„๋กœ ์•ˆํ–ˆ์œผ๋‹ˆ.. 6๋…„๋งŒ? ์ธ๊ฑฐ๊ฐ™๋‹ค ใ… ), Swift๋ฅผ ๊ณต๋ถ€ํ•˜๊ธฐ ์œ„ํ•ด ์‹œ์ž‘ํ–ˆ๋‹ค๋Š” ์  ๋•Œ๋ฌธ์— Level 1 ๋‚œ์ด๋„ ๋ฌธ์ œ์—์„œ ๊ณจ๋ผํ’€๊ณ  ์žˆ๋‹ค..ํ•˜ํ•˜ ๐Ÿ˜‚ ๊ทธ์ค‘์—์„œ๋„ ์ด ๋ฌธ์ œ๋Š” ์‰ฌ์› ๋˜ ๋ฌธ์ œ ๊ฐ™๋‹ค. ๊ทธ๋Ÿฌ๋‚˜.... ์—ญ์‹œ ๋‹ค๋ฅธ์‚ฌ๋žŒ์˜ ํ’€์ด๋ฅผ ๋ดค์„๋•Œ ์ด๋Ÿด ์ˆ˜๋„ ์žˆ๊ตฌ๋‚˜.. ์‹ถ์€๊ฑด ์žˆ๋‹ค ใ… ใ…  ์ด๋ฒˆ์—๋„ map์„ ์‚ฌ์šฉํ–ˆ๋‹ค๋ฉด result๋ผ๋Š” ๋ฐฐ์—ด๋„ ํ•„์š”์—†์—ˆ์„ ๊ฒƒ ๊ฐ™๊ณ , ์ฝ”๋“œ๋„ ๊ฐ„๊ฒฐํ–ˆ์„ ๊ฒƒ ๊ฐ™๋‹ค. ์•„๋ž˜์ฒ˜๋Ÿผ ํ•œ๋ฒˆ ๋Œ๋ ค๋ดค๋Š”๋ฐ, ์ž˜ ๋œ๋‹ค ๐Ÿ˜๐Ÿ˜ ๋‚œ์ด๋„ ์˜ฌ๋ ค์„œ ๋ฌธ์ œ ํ’€๋ ค๋ฉด map, filter์— ๋นจ๋ฆฌ ์ต์ˆ™ํ•ด์งˆ ํ•„์š”๊ฐ€ ์žˆ๋‹ค. ๐Ÿ‘Š

import Foundation

func solution(_ array:[Int], _ commands:[[Int]]) -> [Int] {
    return commands.map { array[$0[0]-1...$0[1]-1].sorted()[$0[2]-1] }
}

 

 

์ถœ์ฒ˜ : ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค K๋ฒˆ์งธ์ˆ˜

Comments