ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - n^2 ๋ฐฐ์—ด ์ž๋ฅด๊ธฐ

2022. 10. 13. 15:25ใ†ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค-Swift

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - n^2 ๋ฐฐ์—ด ์ž๋ฅด๊ธฐ

 

 

 ๋ฌธ์ œ ์„ค๋ช…

 

https://school.programmers.co.kr/learn/courses/30/lessons/87390

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

 ๋‚˜์˜ ํ’€์ด

 

์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋‚ ๊ฑฐ๋ผ๊ณ  ์ƒ๊ฐํ–ˆ์ง€๋งŒ ๋ฌธ์ œ๊ฐ€ ๋งํ•˜๋Š”๋Œ€๋กœ ๊ตฌํ˜„์„ ํ•ด๋ณด๊ณ  ์‹ถ์–ด์„œ ํ•œ ํ’€์ด์ด๋‹ค.

 

import Foundation

func solution(_ n:Int, _ left:Int64, _ right:Int64) -> [Int] {
    
    var arr3 = [[Int]](repeating: [Int](repeating: 0, count: n), count: n)
    var result: [[Int]] = [[]]
    arr3[0][0] = 1
    
    for i in 1..<n {
        for j in 0..<i {
            arr3[i][j] = i+1
            arr3[j][i] = i+1
        }
        arr3[i][i] = i+1
    }
    
    arr3.forEach { arr in
        result.append(arr)
    }
    
    let mapArr = result.flatMap {$0}
    return Array(mapArr[Int(left)...Int(right)])
}

 

์ด ํ’€์ด ์ดํ›„์— ํŠน์ • ์ธ๋ฑ์Šค์ผ๋•Œ ํŠน๋ณ„ํ•œ ๊ทœ์น™์ด ์žˆ๋Š” ๊ฑธ ์•Œ์•˜๋‹ค.

์˜ˆ์‹œ๋กœ n์ด 4์ผ๋•Œ

0ํ–‰ -> 1234

1ํ–‰  -> 2234

2ํ–‰  -> 3334

3ํ–‰  -> 4444

 

๊ทธ๋ž˜์„œ left์™€ right์˜ ํ–‰์„ ๊ตฌํ•˜๊ณ  ๊ทธ ์‚ฌ์ด์— ์žˆ๋Š” ๋ฒ”์œ„๋งŒํผ์˜ ๋ฐฐ์—ด์„ ์œ„์˜ ๊ทœ์น™์„ ์ด์šฉํ•ด์„œ 1์ฐจ์› ๋ฐฐ์—ด์— ๋„ฃ์—ˆ๋‹ค.

๋งŒ๋“ค์–ด์ง„ 1์ฐจ์› ๋ฐฐ์—ด์€ left์— ํ•ด๋‹นํ•˜๋Š” ์ธ๋ฑ์Šค ํ–‰์˜ ์ฒซ๋ฒˆ์งธ ์›์†Œ๋ถ€ํ„ฐ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ๊ทธ ์ „๊นŒ์ง€์˜ ๊ฐ’์ธ ํ–‰์˜ ์ˆ˜ * n๋งŒํผ์„ ๋นผ์ฃผ์–ด ์ผ์น˜์‹œ์ผฐ๋‹ค.

 

import Foundation

func solution(_ n:Int, _ left:Int64, _ right:Int64) -> [Int] {
    var arr: [Int] = []
    var left = Int(left)
    var right = Int(right)
    
    let startRow = left / n
    let endRow = right / n
    
    for i in startRow...endRow {
        for _ in 0...i {
            arr.append(i+1)
        }
        for k in i+1..<n {
            arr.append(k+1)
        }
    }
    let startIdx = left - (startRow * n)
    let endIdx = right - (startRow * n)
    return Array(arr[startIdx...endIdx])
    
}

 

์œ„ ํ’€์ด๊ฐ€ ๋™์ž‘ํ•  ์ˆ˜ ์žˆ๋Š” ์ด์œ ๋Š” left์™€ right์˜ ์ฐจ์ด๊ฐ€ 10^5์ดํ•˜์ด๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. 

 

 

 ๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ํ’€์ด

 

arr[0][0] = 1์ด๊ณ , arr[1][0], arr[0][1], arr[1][1] = 2์ธ ๊ฒƒ์„ ๋ณด๊ณ  i์™€ j์ค‘ ๋” ํฐ ๊ฒƒ + 1์ด ๋ฐฐ์—ด์˜ ๊ฐ’์ธ ๊ฒƒ์„ ์ด์šฉํ•œ ํ’€์ด์ด๋‹ค.

 

๋ฐฐ์—ด์˜ ํ–‰์€ i / n, ์—ด์€ i % n์ธ ๊ฒƒ์„ ์•Œ๋ฉด ๋ฐ”๋กœ ์ƒ๊ฐํ–ˆ์„ ๊ฒƒ ๊ฐ™์€๋ฐ ๋‚˜๋Š” ๋ฐ”๋กœ ์ƒ๊ฐํ•˜์ง€ ๋ชปํ–ˆ๋‹ค.

์ด ๊ตฌ์กฐ๋ฅผ ์ˆ™์ง€ํ•˜๊ณ  ๊ฐ€๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™๋‹ค.

 

import Foundation

func solution(_ n:Int, _ left:Int64, _ right:Int64) -> [Int] {
    var left = Int(left)
    var right = Int(right)
    
    return Array(left...right).map{
        return max($0 / n + 1, $0 % n + 1)
    }
}