슬기로운슬기

문제

[정렬]

https://school.programmers.co.kr/learn/courses/30/lessons/68644

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

해설

import java.util.*;

class Solution {
    public int[] solution(int[] numbers) {
        // 주어진 배열에서 두 수의 합을 모두 구하고 중복을 제거한 결과를 반환하는 메서드

        // 중복을 제거하기 위해 Set 사용
        Set<Integer> answer = new LinkedHashSet<>();

        // 배열을 순회
        for (int i = 0; i < numbers.length - 1; i++) {
            for (int j = i + 1; j < numbers.length; j++) {
                // Set(중복허용X)에 두 수의 합 저장
                answer.add(numbers[i] + numbers[j]);
            }
        }

        // Set을 정렬하고 배열로 변환하여 반환
        return answer.stream().sorted().mapToInt(Integer::intValue).toArray();
    }
}
  • answer.stream(): Set을 스트림으로 변환
  • sorted(): 스트림의 요소 정렬(오름차순)
  • mapToInt(Integer::intValue): 각 요소를 int로 매핑 (Integer 객체 -> int로 변환)
  • toArray(): 스트림의 요소들을 배열로 변환
반응형
profile

슬기로운슬기

@스를기

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!