JAVAIARY

프로그래머스 ) 두 개 뽑아서 더하기 본문

examplePractice

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

shiherlis 2023. 5. 29. 13:20

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

 

프로그래머스

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

programmers.co.kr

 

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

class Solution {
    public ArrayList<Integer> solution(int[] numbers) {
		ArrayList<Integer> answer = new ArrayList<>();
		Arrays.sort(numbers);
		for (int i = 0; i < numbers.length; i++) {
			for (int j = i + 1; j < numbers.length; j++) {
				if (!answer.contains(numbers[i] + numbers[j])) {
					answer.add(numbers[i] + numbers[j]);
				}
			}
		}
        Collections.sort(answer);
		return answer;
	}
}
  • return 타입을 ArrayList로 바꿔서 Collections.sort를 이용할 수 있도록 함
  • 더하기를 해서 ArrayList에 존재하지 않으면 add해주는 방식(중복 체크)