๋๋์ด ๋จ์ด์ง๋ ์ซ์ ๋ฐฐ์ด/level1/java/ํ๋ก๊ทธ๋๋จธ์ค
https://programmers.co.kr/learn/courses/30/lessons/12910
์ฝ๋ฉํ ์คํธ ์ฐ์ต - ๋๋์ด ๋จ์ด์ง๋ ์ซ์ ๋ฐฐ์ด | ํ๋ก๊ทธ๋๋จธ์ค
array์ ๊ฐ element ์ค divisor๋ก ๋๋์ด ๋จ์ด์ง๋ ๊ฐ์ ์ค๋ฆ์ฐจ์์ผ๋ก ์ ๋ ฌํ ๋ฐฐ์ด์ ๋ฐํํ๋ ํจ์, solution์ ์์ฑํด์ฃผ์ธ์. divisor๋ก ๋๋์ด ๋จ์ด์ง๋ element๊ฐ ํ๋๋ ์๋ค๋ฉด ๋ฐฐ์ด์ -1์ ๋ด์ ๋ฐํํ์ธ์. ์ ํ์ฌํญ arr์ ์์ฐ์๋ฅผ ๋ด์ ๋ฐฐ์ด์ ๋๋ค. ์ ์ i, j์ ๋ํด i ≠ j ์ด๋ฉด arr[i] ≠ arr[j] ์ ๋๋ค. divisor๋ ์์ฐ์์ ๋๋ค. array๋ ๊ธธ์ด 1 ์ด์์ธ ๋ฐฐ์ด์ ๋๋ค. ์ ์ถ๋ ฅ ์ arr divi
programmers.co.kr
< ๋๋์ด ๋จ์ด์ง๋ ์ซ์ ๋ฐฐ์ด >
โ ์ฒ์ ํผ ํ์ด
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
import java.util.Arrays;
class Solution {
public int[] solution(int[] arr, int divisor) {
int[] temp2;
int[] temp = new int[arr.length];
int k=0;
//n์ผ๋ก ๋๋ ์ง๋ ๊ฒ์ temp์ ์ ์ฅ
for(int i=0; i<arr.length; i++){
if(arr[i]%divisor==0){
temp[k]=arr[i];
k++; }
}
//k=0์ผ ๋ 0 ์๋ ๋๋ก ๋๋์ด ์ฒ๋ฆฌ
if(k==0){
temp2 =new int[1];
temp2[0]=-1;
}else{
temp2 =Arrays.copyOfRange(temp,0,k);
Arrays.sort(temp2);
}
return temp2;
}
}
|
โ ์๊ฐ๊ณผ์
1.divisor๋ก ๋๋์ด์ง๋ ์๋ฅผ temp ๋ฐฐ์ด์ ๋ฃ๋๋ค
2.temp์ ๊ธธ์ด๋ฅผ arr.length๋ก ํด์ ๋ด๊ธฐ์ง ์์ ์ชฝ์ด 0์ผ๋ก ์ด๊ธฐํ ๋๊ธฐ ๋๋ฌธ์ ์ ๋ ฌ์์ 0๋ ์ ๋ ฌ ๋๊ธฐ ๋๋ฌธ์ K๋ก ๊ฐ์ด ๋ฃ์ด ์ง๋ ๋ง๋ค ์นด์ดํธ ํด์ k๊ฐ์ผ๋ก temp2์ ๋ณต์ฌํด์ค๋ค.
3.Arrays.sort() ๋ฉ์๋๋ฅผ ํตํด์ ์ ๋ ฌํ๋ค.
โ ๊ฐ์ด ๋ณด๊ณ ์ถ์ ํ์ด
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import java.util.Arrays;
class Divisible {
public int[] divisible(int[] array, int divisor) {
//ret์ array์ ํฌํจ๋ ์ ์์ค, divisor๋ก ๋๋์ด ๋จ์ด์ง๋ ์ซ์๋ฅผ ์์๋๋ก ๋ฃ์ผ์ธ์.
return Arrays.stream(array).filter(factor -> factor % divisor == 0).toArray();
}
// ์๋๋ ํ
์คํธ๋ก ์ถ๋ ฅํด ๋ณด๊ธฐ ์ํ ์ฝ๋์
๋๋ค.
public static void main(String[] args) {
Divisible div = new Divisible();
int[] array = {5, 9, 7, 10};
System.out.println( Arrays.toString( div.divisible(array, 5) ));
}
}
|
cs |
โ ๋ค์ ํผ ํ์ด
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
|
import java.util.Arrays;
class Solution {
public int[] solution(int[] arr, int divisor) {
int[] temp =new int[arr.length];
int[] answer;
int cnt=0;
for(int i =0; i<arr.length;i++){
if(arr[i]%divisor==0){
temp[cnt]=arr[i];
cnt++;
}
}
if(cnt==0){
answer =new int[1];
answer[0]=-1;
}else {
answer =new int[cnt];
for(int i=0; i<temp.length; i++){
if(temp[i]!=0)
answer[i]=temp[i];
}
}
Arrays.sort(answer);
return answer;
}
}
|
cs |