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

김현진·2022년 1월 15일
0

코테준비

목록 보기
3/22

문제 링크 - https://programmers.co.kr/learn/courses/30/lessons/68644

  • 해결 방법
    • 주어진 배열의 2개의 수를 합하여 결과를 오름차순으로 배열에 담는 문제이다.
      먼저 각 수를 합했을 때 중복 값이 나타날 수 있으므로 중복을 허용하지 않는
      자료구조인 Set을 활용하기로 했다.
      1. 배열에서 2개의 수를 골라 더한 후 Set에 담는다.
      2. Set을 stream을 이용하여 정렬해 배열로 반환한다.
import java.util.*;

class Solution {
    public int[] solution(int[] numbers) {
        HashSet<Integer> set = new HashSet();
        
        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에 저장
            }
        }

        return set.stream().sorted().mapToInt(Integer::intValue)
        .toArray(); //stream으로 정렬 후 array로 반환
        
    }
}

0개의 댓글