250x250
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 알고리즘
- 재귀함수
- 중복순열
- 알고리즘개념
- 코테
- 주사위굴리기2
- 23288
- java
- 전화번호속의암호
- 볼륨 만들기
- 백준2251
- 정올 1620
- Bfs와DFS
- 삼성역테
- N과M
- 에라토스테네스의채
- 백준13458
- BFS
- 완탐
- 순열
- 백준
- 파티션 크기 조정
- D드라이브생성
- 자바 코테
- 백준15652
- 중복조합
- 정보처리기사
- 코테준비
- 완전탐색
- 자바
Archives
- Today
- Total
뚱땅뚱땅
[문제] 프로그래머스 레벨 1: 두 개 뽑아서 더하기 본문
728x90
programmers.co.kr/learn/courses/30/lessons/68644
코딩테스트 연습 - 두 개 뽑아서 더하기
정수 배열 numbers가 주어집니다. numbers에서 서로 다른 인덱스에 있는 두 개의 수를 뽑아 더해서 만들 수 있는 모든 수를 배열에 오름차순으로 담아 return 하도록 solution 함수를 완성해주세요. 제한
programmers.co.kr
풀이
입력받는 숫자들 중 2개를 뽑아서 set에 저장하면 된다.
이때 나는 재귀를 이용한 조합 함수를 만들었는데, 어차피 2개의 수니까 그럴 필요 없이 for문으로 풀어도 된다.
1. 조합 (재귀 이용)
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
class Solution {
static int N;
static Set<Integer> set = new HashSet<>();
public int[] solution(int[] numbers) {
N = numbers.length;
combination(0,new int[2],0,numbers);
int[] answer = new int[set.size()];
Iterator<Integer> it = set.iterator();
int i=0;
while(it.hasNext()) {
answer[i++] = it.next();
}
Arrays.sort(answer);
return answer;
}
static void combination(int toSelect, int[] selected, int startIdx,int[] numbers){
if(toSelect == 2){
set.add(selected[0]+ selected[1]);
return;
}
for(int i=startIdx;i<N;i++){
selected[toSelect] = numbers[i];
combination(toSelect+1, selected, i+1, numbers);
}
}
}
2. for문 이용
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
class Solution {
public int[] solution(int[] numbers) {
Set<Integer> set = new HashSet<>();
int N = numbers.length;
for(int i= 0;i<N-1;i++){
for(int j=i+1;j<N;j++){
set.add(numbers[i]+numbers[j]);
}
}
int[] answer = new int[set.size()];
Iterator<Integer> it = set.iterator();
int i = 0;
while(it.hasNext()){
answer[i++] = it.next();
}
Arrays.sort(answer);
return answer;
}
}
728x90
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[문제] 프로그래머스 레벨 3: 단어 변환 (0) | 2021.03.23 |
---|---|
[문제] 프로그래머스 레벨1: 모의고사 (0) | 2021.02.15 |
[문제] 프로그래머스 레벨 1: 가운데 글자 가져오기 (0) | 2021.02.15 |
Comments