๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
3๏ธโƒฃ Swift/Problem Solving

[Swift Algorithm] ๋‚˜๋ˆ„์–ด ๋–จ์–ด์ง€๋Š” ์ˆซ์ž ๋ฐฐ์—ด Programmers(Lv.1)

by seolhee2750 2021. 6. 17.
๋ฌธ์ œ ์„ค๋ช…

array์˜ ๊ฐ element ์ค‘ divisor๋กœ ๋‚˜๋ˆ„์–ด ๋–จ์–ด์ง€๋Š” ๊ฐ’์„ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•œ ๋ฐฐ์—ด์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜, solution์„ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”.
divisor๋กœ ๋‚˜๋ˆ„์–ด ๋–จ์–ด์ง€๋Š” element๊ฐ€ ํ•˜๋‚˜๋„ ์—†๋‹ค๋ฉด ๋ฐฐ์—ด์— -1์„ ๋‹ด์•„ ๋ฐ˜ํ™˜ํ•˜์„ธ์š”.

 

์ œํ•œ ์กฐ๊ฑด
  • arr์€ ์ž์—ฐ์ˆ˜๋ฅผ ๋‹ด์€ ๋ฐฐ์—ด์ž…๋‹ˆ๋‹ค.
  • ์ •์ˆ˜ i, j์— ๋Œ€ํ•ด i ≠ j ์ด๋ฉด arr[i] ≠ arr[j] ์ž…๋‹ˆ๋‹ค.
  • divisor๋Š” ์ž์—ฐ์ˆ˜์ž…๋‹ˆ๋‹ค.
  • array๋Š” ๊ธธ์ด 1 ์ด์ƒ์ธ ๋ฐฐ์—ด์ž…๋‹ˆ๋‹ค.

 

์ž…์ถœ๋ ฅ ์˜ˆ
arr divisor return
[5, 9, 7, 10] 5 [5, 10]
[2, 36, 1, 3] 1 [1, 2, 3, 36]
[3,2,6] 10 [-1]

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
func solution(_ arr:[Int], _ divisor:Int) -> [Int] {
    var result = [Int]()

    for i in 0..<arr.count {
        if arr[i] % divisor == 0 {
            result.append(arr[i])
        }
    }
    
    return result.isEmpty ? [-1] : result.sorted(by : <)
}
  • ๋ฐฐ์—ด ์›์†Œ๋“ค์„ ํ•˜๋‚˜์”ฉ ๋‚˜๋ˆ ๋ณด๋ฉฐ ๋‚˜๋ˆ  ๋–จ์–ด์ง€๋Š” ์ˆ˜๋“ค์„ result ๋ฐฐ์—ด์— append
  • ๋ฐฐ์—ด์ด ๋น„์—ˆ๋‹ค๋ฉด [-1] ๋ฆฌํ„ด, ์•„๋‹ˆ๋ฉด ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ๋œ ๋ฐฐ์—ด๋กœ ์ถœ๋ ฅ!

 

์ธ์ƒ์ ์ธ ํ’€์ด
func solution(_ arr:[Int], _ divisor:Int) -> [Int] {
    let array = arr.sorted().filter{ $0 % divisor == 0 }
    return  array == [] ? [-1] : array
}
  • filter ์ด์šฉํ•˜์—ฌ ๋‚˜๋ˆ  ๋–จ์–ด์ง€๋Š” ์ˆ˜๋“ค์˜ ๋ฐฐ์—ด ์ƒ์„ฑํ•ด์ฃผ๊ณ  ์ •๋ ฌํ•ด์ฃผ์—ˆ๋‹ค.

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • ์—ญ์‹œ ๊ณ ์ฐจํ•จ์ˆ˜๋ฅผ ์ž˜ ์ด์šฉํ•˜๋Š”๊ฒŒ ์ฝ”๋“œ๋ฅผ ์กฐ๊ธˆ์ด๋ผ๋„ ๊ฐ„๊ฒฐํžˆ ์ž‘์„ฑํ•˜๋Š”๋ฐ์— ํฐ ๋„์›€์ด ๋˜๋Š” ๋“ฏ ํ•˜๋‹ค.!!

 


 

๐Ÿ– [ ์ถ”๊ฐ€ ] 1์ฃผ์ผ ํ›„ ๋‹ค์‹œ ํ’€์–ด๋ณด๊ธฐ

func solution(_ arr:[Int], _ divisor:Int) -> [Int] {
    var res = Array(arr.filter({$0%divisor == 0}))
    return res.isEmpty ? [-1] : res.sorted()
}
  • ํ›จ์”ฌ ๊น”๋”ํ•˜๊ฒŒ ํ’€์—ˆ๋‹ค,,
  • ํ™•์‹คํžˆ ์ด์ œ ๊ณ ์ฐจํ•จ์ˆ˜ ์‚ฌ์šฉ์— ํ›จ์”ฌ ์ต์ˆ™ํ•ด์กŒ๋‹ค. 

 


 

๋ฌธ์ œ

https://programmers.co.kr/learn/courses/30/lessons/12910

 

๋Œ“๊ธ€