1. 문제 설명
2. 나의 풀이
class Solution {
public int[] solution(int n, int[] numlist) {
int[] tempAnswer = new int[numlist.length];
int temp = 0;
for(int i = 0; i < numlist.length; i++)
{
if(numlist[i] % n == 0)
{
tempAnswer[temp] = numlist[i];
temp ++;
}
}
int[] answer = new int[temp];
for(int i = 0; i < answer.length; i++)
{
answer[i] = tempAnswer[i];
}
return answer;
}
}
3. 다른 사람의 풀이
1. 내 풀이와 비슷하지만 효율적인 코드
class Solution {
public int[] solution(int n, int[] numlist) {
int count = 0;
for(int i : numlist){
if(i%n==0){
count++;
}
}
int[] answer = new int[count];
int idx = 0;
for(int i : numlist){
if(i%n==0){
answer[idx]=i;
idx++;
}
}
return answer;
}
}
위쪽 포문에서는 그냥 크기만 알아내고(그러므로 temp배열이 하나 더 필요 없다),
아래쪽 포문에서 n의 배수만 알아내서 다시 대입하는 방법
2.리턴값을 바꿔 배열 크기를 알아낼 필요 없는 방법
import java.util.*;
class Solution {
public ArrayList solution(int n, int[] numlist) {
ArrayList<Integer> answer = new ArrayList<>();
for(int num : numlist){
if(num % n == 0){
answer.add(num);
}
}
return answer;
}
}
리턴값을 꼭 int[] 로 안해도 된다면
ArrayList 를 사용하여 배열 크기를 알아낼 필요 없이 바로 add로 추가하기
'코테 > java' 카테고리의 다른 글
[프로그래머스][java] lv 0 주사위의 개수 (0) | 2024.11.27 |
---|---|
[프로그래머스][java] lv 0 공 던지기 (0) | 2024.11.23 |
[프로그래머스][java] lv 0 구슬을 나누는 경우의 수 (0) | 2024.11.22 |
[프로그래머스][java] lv 0 모스부호(1) (0) | 2024.11.21 |
[프로그래머스][java] lv 0 진료순서 정하기 (0) | 2024.11.21 |