ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Programmers] Lv1.N^2 ๋ฐฐ์—ด ์ž๋ฅด๊ธฐ(Kotlin)
    SW Test/Programmers 2021. 11. 15. 22:27
    ๋ฐ˜์‘ํ˜•
    • ์ด ๋ฌธ์ œ๋Š” kotlin์œผ๋กœ ํ’€์ด๋ฅผ ์ž‘์„ฑํ•˜์˜€์Šต๋‹ˆ๋‹ค.

    ๋ฌธ์ œ

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

     

    ์˜ˆ์‹œ

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

     

    ํ’€์ด

    • ๋ฐฐ์—ด์„ ๊ตฌํ•œ ํ›„์— ๋‹ต์„ ๊ตฌํ•˜๋ฉด ์‰ฝ๊ฒŒ ๊ตฌํ•  ์ˆ˜ ์žˆ์ง€๋งŒ ์‹œ๊ฐ„์ดˆ๊ณผ๋ฅผ ํ”ผํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.
    • ํ•ด๋‹น ๋ฌธ์ œ๋Š” ๋ฐฐ์—ด์„ ๊ตณ์ด ๊ตฌํ•  ํ•„์š”์—†์ด ๊ทœ์น™์„ ์ž˜ ํŒŒ์•…ํ•˜๋ฉด ์›ํ•˜๋Š” ์ง€์ ๋ถ€ํ„ฐ ๊ฐ’์„ ๊ตฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
    • 1๋ฒˆ์งธ ํ–‰์—์„œ๋Š” 1๋ฒˆ์งธ ์—ด๊นŒ์ง€ 1๋กœ ์ฑ„์šฐ๊ณ  ์ดํ›„๋ถ€ํ„ฐ๋Š” 1์”ฉ ์ฆ๊ฐ€ํ•ฉ๋‹ˆ๋‹ค.
      2๋ฒˆ์งธ ํ–‰์—์„œ๋Š” 2๋ฒˆ์งธ ์—ด๊นŒ์ง€ 2๋กœ ์ฑ„์šด ํ›„ 1์”ฉ ์ฆ๊ฐ€ํ•ฉ๋‹ˆ๋‹ค.
      ...
      n๋ฒˆ์งธ ํ–‰์—์„œ๋Š” n๋ฒˆ์งธ ์—ด๊นŒ์ง€ n์œผ๋กœ ์ฑ„์›๋‹ˆ๋‹ค.
    class Solution {
        fun solution(n: Int, left: Long, right: Long): IntArray {
            var answer = mutableListOf<Long>()
            
            var start_row = left/n; var start_col = left%n
            var end_row = right/n; var end_col = right%n;
            
            if(start_row == end_row){
                for(i in start_col..end_col){
                    if(i<=start_row) answer.add(start_row + 1)
                    else answer.add(i+1)
                }
            }else{
                for(i in start_col until n){
                    if(i<=start_row) answer.add(start_row + 1)
                    else answer.add(i+1)
                }
                
                for(i in start_row+1 until end_row){
                    for(j in 0 until n.toLong()){
                        if(j<=i) answer.add(i+1)
                        else answer.add(j+1)
                    }
                }
                
                for(i in 0..end_col){
                    if(i<=end_row) answer.add(end_row+1)
                    else answer.add(i+1)
                }
            }
            
            return answer.map { it.toInt()}.toIntArray();
        }
    }

     

    • ์œ„์— ๊ทœ์น™์„ ์ž˜ ์ƒ๊ฐํ•˜๋ฉด index/n ๊ณผ index%n ์ค‘์—์„œ ์ตœ๋Œ“๊ฐ’์ด ๋ฐฐ์—ด์˜ ๊ฐ’์ด ๋œ๋‹ค๋Š” ๊ฒƒ์„ ์•Œ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
    • ํ•ด๋‹น ๋ฌธ์ œ ํ’€์ด ์‹œ intArray์™€ ArrayList<Int> ๋ฅผ ์ž˜ ๊ตฌ๋ณ„ํ•˜์—ฌ ์‚ฌ์šฉํ•˜๋ฉด ํŽธ๋ฆฌํ•˜๊ฒŒ ํ’€ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
    import kotlin.math.max
    
    class Solution {
        fun solution(n: Int, left: Long, right: Long): IntArray {
            return (left..right).map{ (max(it/n, it%n)+1).toInt() }.toIntArray()
        }
    }

     

     

    ๋ฐ˜์‘ํ˜•
Designed by Tistory.