[알고리즘문제풀기] n의 배수 고르기

silver's avatar
Dec 27, 2024
[알고리즘문제풀기] n의 배수 고르기

문제

내가 작성한 정답

import java.util.*; class Solution { public int[] solution(int n, int[] numlist) { List<Integer> list = new ArrayList<>(); for(int a : numlist){ if(a%n==0){ list.add(a); } } int[] answer = new int[list.size()]; int index = 0; for(int b : list){ answer[index++] = b; } return answer; } }

StreamAPI

import java.util.*; class Solution { public int[] solution(int n, int[] numlist) { return Arrays.stream(numlist) .filter(a->a%n==0) .toArray(); } }
 
💡
Stream정리
list를 스트림에 던지려면 stream()
배열을 스트림에 던지려면 Arrays.stream(Array)
.toList(); → 스트림의 요소 List로 변환
.toArray(); → 스트림의 요소 배열로 변환

다른 사람들의 정답

import java.util.List; import java.util.ArrayList; class Solution { public int[] solution(int n, int[] numlist) { List<Integer> answer = new ArrayList<>(); for(int num : numlist){ if(num % n == 0){ answer.add(num); } } return answer.stream().mapToInt(x -> x).toArray(); } }
 
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; } }
Share article

silver