일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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
- 생명주기 콜백
- JPA
- JWT
- Project
- html
- bean
- WIL
- DI
- oauth
- flask
- cookie
- Anolog
- spring
- jenkins
- 항해99
- python
- Spring Security
- jQuery
- google oauth
- Hibernate
- session
- Stream
- real time web
- SseEmitter
- javascript
- hanghae99
- programmers
- web
- server send event
- Java
Archives
- Today
- Total
끄적끄적 코딩일지
[Programmers]두개 뽑아서 더하기(난이도:★★★★) 본문
https://programmers.co.kr/learn/courses/30/lessons/68644
코딩테스트 연습 - 두 개 뽑아서 더하기
정수 배열 numbers가 주어집니다. numbers에서 서로 다른 인덱스에 있는 두 개의 수를 뽑아 더해서 만들 수 있는 모든 수를 배열에 오름차순으로 담아 return 하도록 solution 함수를 완성해주세요. 제한
programmers.co.kr
import java.util.ArrayList;
class Solution {
public int[] solution(int[] numbers) {
return solutionA(numbers);
}
// 단순 리스트 사용
public int[] solutionA(int[] numbers){
ArrayList<Integer> arry = new ArrayList<>();
for(int i = 0 ; i < numbers.length;i++){
for(int j = 0 ; j < numbers.length; j++){
if(i == j)
continue;
int num = numbers[i] + numbers[j];
if(!arry.contains(num))
arry.add(num);
}
}
arry.sort(null);
int[] ret = new int[arry.size()];
for(int i= 0 ; i < arry.size(); i++)
ret[i] = arry.get(i);
return ret;
}
// 배열만 사용
public int[] solutionB(int [] numbers){
int idx= 0;
int[] allSets = new int [numbers.length * (numbers.length-1)];
for(int i = 0 ; i < numbers.length;i++){
for(int j = 0 ; j < numbers.length; j++){
if(i == j)
continue;
int num = numbers[i] + numbers[j];
allSets[idx] = num;
idx++;
}
}
return removeDuplicate(allSets);
}
//중복 제거
public int[] removeDuplicate(int[] arry){
int counter = 1;
bubbleSort(arry);
// 중복제거한 배열의 크기 계산
for(int i = 0; i < arry.length-1; i++){
if(arry[i] != arry[i+1])
counter++;
}
// 중복 제거 배열 생성
int[] res = new int[counter];
int idx = 0;
for(int i = 0;i < arry.length-1; i++){
if(arry[i] != arry[i+1]){
res[idx] = arry[i];
idx++;
}
}
res[idx] = arry[arry.length-1];
return res;
}
// 버블 정렬
public void bubbleSort(int[] arry){
int idx = arry.length -1;
for(int i = 0 ; i < arry.length; i++){
for(int j = 0; j < idx; j++){
if(arry[j] > arry[j+1]){
int tmp = arry[j];
arry[j] = arry[j+1];
arry[j+1] = tmp;
}
}
idx--;
}
}
}
'알고리즘' 카테고리의 다른 글
[Programmers]모의고사(난이도:★★★★) (0) | 2022.05.16 |
---|---|
[Programmers]로또의 순위(난이도:★★★★) (0) | 2022.05.16 |
[Programmers]같은 숫자는 싫어(난이도:★★★★) (0) | 2022.05.16 |
[Programmers]최소 직사각형(난이도:★★★★) (0) | 2022.05.16 |
[Programmers]3진법 뒤집기(난이도:★★★★) (0) | 2022.05.16 |