일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 | 31 |
- 백준 1967번 트리의 지름 G4 자바
- 스프링 on-profile
- 프로그래머스 java
- HashSet
- 프로그래머스 자바
- StringBuilder
- append
- 서브모듈 yml
- dp
- HashMap
- Stack
- 포인트 컷
- 전위 중위 후위
- 백준 1240번 노드사이의 거리
- 백준 8979번 올림픽 S5 자바
- 스프링 다중프로필
- 백준 2660번 회장뽑기 G5
- toUpperCase
- replace()
- 백준 1600번 말이 되고픈 원숭이
- 백준 11725번 트리의 부모 찾기
- StringTokenizer
- 프로그래머스
- hash
- kotlin
- 백준 2589번 보물섬 G5
- map
- Java
- 백준 2206번 벽 부수고 이동하기 G3
- 코틀린기초
- Today
- Total
말하는 컴공감자의 텃밭
프로그래머스 - 두 개 뽑아서 더하기 (자바) java Hashset 본문
먼저 반복으로 배열에서 두개 인자를 뽑아 더하고, 중복이 아니라면 배열에 넣은 후 Arrays.sort로 정리해주기로 했다.
중복을 막기위해 HashSet을 사용~!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import java.util.*; class Solution { public int[] solution(int[] numbers) { Set<Integer> set = new HashSet<Integer>(); int n = numbers.length; for (int i = 0; i<n; i++){ for ( int j = i+1; j<n; j++){ set.add(numbers[i] + numbers[j]); } } int[] answer = new int[set.size()]; int k = 0; for( int num : set){ answer[k++] = num; } Arrays.sort(answer); return answer; } } | cs |
Set<Integer> set = new HashSet<Integer>(); // Set 인터페이스 중 중복과 순서를 고려하지 않는 Hash를 사용.
for (int i = 0; i<n; i++){
for ( int j = i+1; j<n; j++){
set.add(numbers[i] + numbers[j]); // 반복문을 통해 배열에서 요소 두개를 더해 set에 add
}
}
int[] answer = new int[set.size()]; // set에 넣은 사이즈로 answer 초기화.
int k = 0; // 인덱스
for( int num : set){
answer[k++] = num; // num 변수에 set에 저장된 값을 하나씩 전달. answer 배열에 저장
}
Arrays.sort(answer); // 배열 오름차순 정리
스트림을 사용하는 경우도 있는데 이게 뭔가 싶다.. 공부 해봐야겠다..
'알고리즘 > Programmers - Java' 카테고리의 다른 글
프로그래머스 마지막 두 원소 - 자바 (java) Arrays.copyOf (0) | 2023.04.29 |
---|---|
프로그래머스 - 폰켓몬 자바(java) Hash (0) | 2023.04.26 |
프로그래머스 문자열 겹치기 - 자바(java) replace, StringBulider (0) | 2023.04.21 |
프로그래머스 외계어 사전 - 자바(java), HashSet (1) | 2023.04.21 |
프로그래머스 - 대소문자 바꿔서 출력하기 자바(java) (0) | 2023.04.20 |