본문 바로가기
프로그래머스 Algorithm

[프로그래머스] 연속 부분 수열 합의 개수 Kotlin

by Echung 2023. 12. 30.

thumbnail

안녕하세요. 이번에는 프로그래머스 연속 부분 수열 합의 개수 문제를 풀어보려고 합니다. 

Problem


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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

Solution


class Solution {
    fun solution(elements: IntArray): Int {
        var hashSet = HashSet<Int>()
        val arr = elements.clone() + elements.clone()
        
        (1..elements.size).forEach { i ->
            elements.forEachIndexed { index , int ->
                hashSet.add(arr.sliceArray(index until index + i).sum())        
            }
        }
    
    
        return hashSet.size
    }
}

이번 문제는 hashSet을 사용해서 중복처리를 하는 방법으로 문제를 접근해 보았습니다. forEachIndexed를 사용해서 arr를 잘라주고 그 값들을 set에 추가하는 방법입니다.

 

1. 다른 사람 코드

class Solution {
     fun solution(elements: IntArray): Int {
        val doubling = elements + elements
        val result = HashSet<Int>()

        for(i in 0..elements.size - 1) {
            result.addAll((elements.indices).map {
                doubling.slice(it .. it + i).sum()
            })
        }

        return result.size
    }
}
이번 문제의 다른 사람 코드는 저의 코드와 비슷하게 문제를 푼 것을 확인할 수 있었습니다.

Performance

1. 내가 작성한 코드 2. 다른 사람 코드
반응형