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

2023. 2. 9. 18:27알고리즘

728x90

문제 설명

정수 배열 numbers가 주어집니다. numbers에서 서로 다른 인덱스에 있는 두 개의 수를 뽑아 더해서 만들 수 있는 모든 수를 배열에 오름차순으로 담아 return 하도록 solution 함수를 완성해주세요.

제한사항

  • numbers의 길이는 2 이상 100 이하입니다.
    • numbers의 모든 수는 0 이상 100 이하입니다.

입출력 예

입출력 예 설명

입출력 예 #1

  • 2 = 1 + 1 입니다. (1이 numbers에 두 개 있습니다.)
  • 3 = 2 + 1 입니다.
  • 4 = 1 + 3 입니다.
  • 5 = 1 + 4 = 2 + 3 입니다.
  • 6 = 2 + 4 입니다.
  • 7 = 3 + 4 입니다.
  • 따라서 [2,3,4,5,6,7] 을 return 해야 합니다.

입출력 예 #2

  • 2 = 0 + 2 입니다.
  • 5 = 5 + 0 입니다.
  • 7 = 0 + 7 = 5 + 2 입니다.
  • 9 = 2 + 7 입니다.
  • 12 = 5 + 7 입니다.
  • 따라서 [2,5,7,9,12] 를 return 해야 합니다.

코드 설명

import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.TreeSet;

public class Solution {
	
	// 방법1 (HashSet 사용, 중복값 제거해주고 정렬은 안됨.)
//	public int[] solution(int[] numbers) {
//        HashSet<Integer> hashSet = new HashSet<>();
//        
//        for (int i = 0; i < numbers.length; i++) {
//        	for (int j = i + 1; j < numbers.length; j++) {
//        		hashSet.add(numbers[i] + numbers[j]); // numbers를 2개씩 다 더해서 저장해줌.
//        	}
//        }
//        int[] answer = hashSet.stream().mapToInt(x -> x).toArray(); 
		  // answer배열에 hashSet에 저장한 값들을 stream을 이용해서 int로 변환 후 toArray이용해서 배열로 저장
//        Arrays.sort(answer); // Arrays.sort이용해서 answer를 정렬해줌.
//        
//        return answer;
//    }
	
	// 방법2 (TreeSet 사용, 중복값 제거해주고 정렬까지 해줌.)
	public int[] solution(int[] numbers) {
		TreeSet<Integer> answer = new TreeSet<>();
		for (int i = 0; i < numbers.length; i++) {
        	for (int j = i + 1; j < numbers.length; j++) { 
        		answer.add(numbers[i] + numbers[j]); // numbers를 2개씩 다 더해서 저장해줌.
        	}
   	     }
		return answer.stream().mapToInt(x -> x).toArray(); // answer를 stream이용해서 int로 변환 후 toArray이용해서 배열로 출력
	}
	public static void main(String[] args) {
		Solution T = new Solution();
		Scanner sc = new Scanner(System.in);
		int num = sc.nextInt();
		int[] numbers = new int[num];
		for (int i = 0; i < num; i++) {
			numbers[i] = sc.nextInt();
		}
		for (int x : T.solution(numbers)) {
			System.out.print(x + " ");
		}
		sc.close();
	}
}
728x90