-
프로그래머스 - 두 개 뽑아서 더하기 [자바]Algorithms/- 프로그래머스 2022. 1. 31. 02:03
- 문제 링크 : 두 개 뽑아서 더하기
정답
import java.util.*; import java.util.stream.*; class Solution { public int[] solution(int[] numbers) { Set<Integer> hs = new HashSet<>(); for(int i=0; i<numbers.length; i++){ for(int j=0; j<numbers.length; j++){ if(i != j){ hs.add(numbers[i] + numbers[j]); } } } int[] answer = hs.stream().mapToInt(Integer::intValue).toArray(); Arrays.sort(answer); return answer; } }
분석
- 단순 set 문제
참고할 만한 정답
- sort까지 한번에 가능한 정답
import java.util.HashSet; import java.util.Set; class Solution { public int[] solution(int[] numbers) { Set<Integer> set = new HashSet<>(); for(int i=0; i<numbers.length; i++) { for(int j=i+1; j<numbers.length; j++) { set.add(numbers[i] + numbers[j]); } } return set.stream().sorted().mapToInt(Integer::intValue).toArray(); } }
반응형