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

nbh·2024년 7월 13일

코테

목록 보기
1/2

문제 이름 두 개 뽑아서 더하기
문제 출처 https://school.programmers.co.kr/learn/courses/30/lessons/68644

문제

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

제한사항

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

내 풀이

import java.util.ArrayList;
import java.util.Arrays;

class Solution {
    public int[] solution(int[] numbers) {
        ArrayList<Integer> result = new ArrayList<>();

        for(int i = 0; i < numbers.length - 1; i++){
            for (int j = i + 1; j < numbers.length; j++){
                result.add(numbers[i] + numbers[j]);
            }
        }

        int[] re = result.stream().mapToInt(Integer::intValue).distinct().toArray();
        Arrays.sort(re);
        return re;
    }
}

코드 설명

문제가 요구하는 계산값을 저장하기 위한 ArrayList를 만들어 모든 경우의 수를 더해 넣었다.
이후 이 ArrayList를 스트림을 통해 배열로 바꾸어 반환하였다.

MEMO

  • mapToInt() : 스트림의 값을 Integer에서 int로 바꿔주고 있다.
  • distinct() : 중복 값이 들어가지 않기 위함
  • Arrays.sort() : Arrays.sort()와 Collection.sort()를 구분하여 사용하도록 하자.

풀이 코드

import java.util.HashSet
class Solution {
    public int[] solution(int[] numbers) {
        HashSet<Integer> result = new HashSet<>();

        for(int i = 0; i < numbers.length - 1; i++){
            for (int j = i + 1; j < numbers.length; j++){
                result.add(numbers[i] + numbers[j]);
            }
        }

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

출처 : 책 '코딩테스트 합격자되기'

이 코드는 내가 작성한 코드와 다르게 두 수를 더한 값을 ArrayList가 아닌 HashSet에 저장하고 있다.
HashSet는 중복된 값을 저장하지 않기 때문에, 따로 중복을 제거하는 코드가 없다.

stream().sorted()를 몰랐어서 배열을 int[]로 만든 뒤 Arrays.sort()를 이용하여 정렬하고 반환했는데, 코드가 좀 지저분하다는 생각이 들었다.

스트림을 더 잘 쓰기 위해 공부해야겠다는 생각이 든다.

0개의 댓글