[프로그래머스] 두 개 뽑아서 더하기

이찬혁·2024년 5월 16일

알고리즘

목록 보기
61/72

프로그래머스 Lv1 - 두 개 뽑아서 더하기 문제

프로그래머스 레벨 1 두 개 뽑아서 더하기 문제를 풀이했다.

문제 자체가 간단해서 중복을 허용하지 않는 set 자료 구조중에서 정렬된 tree 형태로 요소를 저장하는(기본 오름차순 정렬) TreeSet 클래스를 사용하여 간단하게 문제 풀이를 완료했다.

AddTwoElement.java

package com.example.Programmers.Lv1;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

/**
 * 프로그래머스 Lv1 - 두 개 뽑아서 더하기
 */
public class AddTwoElement {
    public int[] solution(int[] numbers) {
        List<Integer> answer = new ArrayList<>();
        Set<Integer> set = new TreeSet<>();

        // 두 요소를 더해 treeSet에 추가(중복 방지 및 오름차순 정렬)
        for (int i = 0; i < numbers.length - 1; i++) {
            for (int j = i + 1; j < numbers.length; j++) {
                set.add(numbers[i] + numbers[j]);
            }
        }

        // set의 요소들을 그대로 리스트에 추가
        for (Integer s : set) {
            answer.add(s);
        }

        return answer.stream().mapToInt(Integer::intValue).toArray();
    }
}

AddTwoElementTest.java

package com.example.Programmers.Lv1;

import static org.junit.Assert.assertArrayEquals;

import org.junit.Test;

public class AddTwoElementTest {
    @Test
    public void testAddTwoElement() {
        AddTwoElement a = new AddTwoElement();

        int[] result1 = a.solution(new int[] { 2, 1, 3, 4, 1 });
        int[] result2 = a.solution(new int[] { 5, 0, 2, 7 });

        int[] expected1 = new int[] { 2, 3, 4, 5, 6, 7 };
        int[] expected2 = new int[] { 2, 5, 7, 9, 12 };

        assertArrayEquals(expected1, result1);
        assertArrayEquals(expected2, result2);
    }
}
profile
나의 개발로그

0개의 댓글