๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm/Kotlin

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค • ์ฝ”ํ‹€๋ฆฐ] ์ตœ์†Œ์ง์‚ฌ๊ฐํ˜• #86491

by ํ‚ค์œค 2023. 11. 27.

#86491

๐ŸŽ„ Question ?

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

class Solution {
    fun solution(sizes: Array<IntArray>): Int {
        var answer: Int = 0
        return answer
    }
}

๐Ÿงฉ Thought Process

  1. ๋ฐฐ์—ด ์•ˆ์— ์žˆ๋Š” ๋ฐฐ์—ด์„ [ํฐ ๊ฐ’, ์ž‘์€๊ฐ’] ์ˆœ์„œ๋กœ ์žฌ ๋ฐฐ์—ด์‹œํ‚ค๊ธฐ
  2. ๋ฐฐ์—ด ์•ˆ์— ์žˆ๋Š” ๋ฐฐ์—ด์˜ (ํฐ ๊ฐ’)์˜ ์ตœ๋Œ“๊ฐ’๊ณผ (์ž‘์€ ๊ฐ’)์˜ ์ตœ๋Œ“๊ฐ’ ๊ตฌํ•˜๊ธฐ
class Solution {
    fun solution(sizes: Array<IntArray>): Int {
        var answer: Int = 0
        var M = mutableListOf<Int>()
        var m = mutableListOf<Int>()
        for (i in sizes.indices) {
            M.add(maxOf(sizes[i][0], sizes[i][1]))
            m.add(minOf(sizes[i][0], sizes[i][1]))
        }
        println(M)
        println(m)
        println(M.sortDescending())
        println(m.sortDescending())
        return 0
    }
}

์ž˜ ํ’€์—ˆ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ๋Š”๋ฐ ์˜ˆ์ƒ์น˜ ๋ชปํ•œ ์—๋Ÿฌ์— ๋ด‰์ฐฉํ–ˆ๋‹ค.. ใ…œ

println()์„ ์ด์šฉํ•ด์„œ ์ค‘๊ฐ„์— ๊ฐ’์ด ์ œ๋Œ€๋กœ ๋‚˜์™”๋Š”์ง€ ํ™•์ธ ํ–ˆ๋‹ค.

sortDescending() ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๊ณ  ๋‚˜๋ฉด ๋ฆฌ์ŠคํŠธ๊ฐ€ Kotlin unit์œผ๋กœ ๋ฐ”๋€Œ๋Š”๋ฐ

์™œ ๋ฐ”๋€Œ๋Š”์ง€ ๋ชจ๋ฅด๊ฒ ๋‹ค. ์ฐพ์•„๋ณด๋‹ˆ kotlin unit์ด java์—์„œ์˜ void์™€ ๊ฐ™๋‹ค๊ณ  ํ•˜๋Š”๋ฐ ๊ทธ๊ฑด ์•ˆ์— ๊ฐ’์ด ์—†๋‹ค๋Š” ๊ฑฐ์ž–์•„?? ๊ทธ๋Ÿฐ๋ฐ ๊ฐ’์ด ์žˆ๋Š”๋ฐ??

๐ŸŽ€ Answer

class Solution {
    fun solution(sizes: Array<IntArray>): Int {
        var big = 0
        var small = 0 
        
        sizes.forEach{
           if(it[0] > it[1]){
               if(big < it[0]) big = it[0]
               if(small < it[1]) small = it[1]
           }else{
               if(big < it[1]) big = it[1]
               if(small < it[0]) small = it[0] 
           }
        }
              
        return big * small 
    }
}
์ถœ์ฒ˜: https://ardor-dev.tistory.com/41 [Ardor IT's Devlog:ํ‹ฐ์Šคํ† ๋ฆฌ]

forEach ํ•จ์ˆ˜๋ฅผ ์ดˆ๊ธฐ์— ์‚ฌ์šฉํ•˜๋ ค๊ณ  ์‹œ๋„ ํ•ด๋ดค๋‹ค๊ฐ€ ์ •ํ™•์ด ์–ด๋–ป๊ฒŒ ์‚ฌ์šฉํ•˜๋Š”๊ฑด์ง€ ๋ชจ๋ฅด๊ฒ ์–ด์„œ ํฌ๊ธฐ๋ฅผ ํ–ˆ๋‹ค. ํ•œ 5๋ถ„ ์งธ๋ ค๋ณด๋‹ˆ๊นŒ ๋Œ€์ถฉ ์ฝ”๋“œ๊ฐ€ ์ดํ•ด๊ฐ€ ๋œ๊ฑฐ ๊ฐ™๋‹ค. ๋‚ด๊ฐ€ ์ ‘๊ทผ ํ•œ ๋ฐฉ์‹์ด๋ž‘ ๊ฐ™์•„์„œ ์ดํ•ดํ•˜๊ธฐ ์‰ฌ์› ๋‹ค.

ํ’€์ด 2

class Solution {
    fun solution(sizes: Array<IntArray>): Int {
        var a = 0
        var b = 0

        for (array in sizes) {
            array.sort()
            if (array.isNotEmpty()) {
                a = array.first().coerceAtLeast(a)
                b = array.last().coerceAtLeast(b)
            }
        }
        return a * b
    }
}
์ถœ์ฒ˜: https://ardor-dev.tistory.com/41 [Ardor IT's Devlog:ํ‹ฐ์Šคํ† ๋ฆฌ]

coerceAtLeast ๋ผ๋Š” ๊ฐ’์„ ๋น„๊ตํ•ด ์ค„ ์ˆ˜ ์žˆ๋Š” ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ–ˆ๋‹ค. 

๋น„๊ตํ•จ์ˆ˜ ์ •๋ฆฌ ๋ฆฌ์ŠคํŠธ ๋งํฌ: https://soeun-87.tistory.com/26

๐ŸŽ Result

๐Ÿ† Comment

forEach ๋ฐ˜๋ณต๋ฌธ ๊ณต๋ถ€๋ฅผ ์ œ๋Œ€๋กœ ํ•ด๋ด์•ผ๊ฒ ๋‹ค. ์–ด๋ ต๋‹ค.