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

etc-image-0

 

import java.util.Arrays;
class Solution {
public int[] solution(int[] numbers) {
// 두개 뽑아서 더하는 로직 시작 // numbers_combination 배열 크기 넓게 시작
int[] numbers_combination = new int[numbers.length*numbers.length];
int combination_count = 0;
for(int i=0; i<numbers.length-1; i++){
for(int j=i+1; j< numbers.length; j++){
numbers_combination[combination_count] = numbers[i]+numbers[j];
combination_count++;
}
}
// 새로운 int배열 생성해서 copyOfRange로 필요한 값만 잘라서 넣기
int[] temp = Arrays.copyOfRange(numbers_combination,0,combination_count);
Arrays.sort(temp); // 정렬
int[] new_temp = new int[temp.length]; // 중복제거 시작
int index = 0;
for(int i=0; i<temp.length-1; i++) {
if (temp[i] != temp[i + 1]) {
new_temp[index] = temp[i];
index++;
}
}
System.out.println(Arrays.toString(new_temp)); // 중복제거를 완료하면 new_temp 빈자리에 0으로 채워짐
new_temp[index++] = temp[temp.length-1]; // 마지막 자리 체크
int[] answer = Arrays.copyOfRange(new_temp,0,index);
// 새로운 int배열 생성해서 copyOfRange로 필요한 값만 잘라서 넣기 = 빈자리 0 버리기
return answer;
}
}