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

Digeut·2023년 10월 25일
0

프로그래머스

목록 보기
109/164

❔문제설명

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

🤔아이디어

for문 2개를 돌려서 i와 j = i+1을 돌리면되지 않을까? 그리고 중복값을 제거해서 정렬시키면 될것같다.

💡코드풀이

import java.util.*;

class Solution {
    public int[] solution(int[] numbers) {
        int[] answer = {};
        HashSet<Integer> set = new HashSet<Integer>();
        ArrayList<Integer> arr = new ArrayList<>();
        //중복값, result 배열의 크기 지정을 어떻게 해야하는지 문제
        for(int i = 0 ; i < numbers.length ; i++){
            for(int j = i + 1 ; j < numbers.length ; j++){
                set.add(numbers[i] + numbers[j]);
            }
        }
        
        answer = new int[set.size()];
        
        for(int a  : set){
            arr.add(a);
        }
        
        Collections.sort(arr); //정렬을위함
        
        int count = 0;
        for(int b : arr){
            answer[count] = b;
            count++;
        }
        
        return answer;
        
    }
}

HashSet을 이용해서 중복값을 제거했다. 그리고 그 set의 사이즈로 answer의 크기를 정하고 하나씩 저장해주었다. 이때 count라는 index를 따로 만들어서 해당 인덱스에 정확하게 들어가게 설정했다.

profile
개발자가 될 거야!

0개의 댓글