TIL #13

loci·2024년 5월 12일
0

TIL

목록 보기
12/103


두 개 뽑아서 더하기
배열에서 두 수를 더한 값을 return
중복된 값이 없어야함


class Solution {
    fun solution(numbers: IntArray): IntArray {
        var answer: IntArray = intArrayOf()
        var set = mutableSetOf<Int>()
        var count = 0
        for( i in numbers){
            for(j in 1+count..numbers.size-1){
                set.add(i + numbers[j])
                
            }
                count++
        }
        return set.sorted().toIntArray()
    }
}

set이 중복을 허용하지 않기 때문에 추출된 값을 set에 저장해 정렬한다.


다른사람의 풀이

class Solution {
    fun solution(numbers: IntArray): IntArray {
        val list = numbers.toList()
        return list.withIndex().flatMap { i -> list.withIndex().map { j -> i to j } }
            .filter { it.first.index != it.second.index }
            .map { it.first.value + it.second.value }
            .toSortedSet()
            .toIntArray()
    }
}
profile
편리한 개발자

0개의 댓글