[프로그래머스] 나누어 떨어지는 숫자 배열

박채은·2023년 5월 14일
0

코딩테스트

목록 보기
39/52

문제

문제 풀이

import java.util.*;

class Solution {
    public int[] solution(int[] arr, int divisor) {
        int len = arr.length;
        int index = 0;
        int[] result = new int[len];
        
        // arr를 divisor로 나누기
        for(int i=0;i<len;i++){
            if(arr[i] % divisor == 0){
                result[index++] = arr[i];
            }
        }
        
        if(index == 0){
            return new int[]{-1};
        }
        
        int[] answer = new int[index];
        for(int i=0;i<index;i++){
            answer[i] = result[i];
        }
        Arrays.sort(answer);
        return answer;
    }
}

다른 사람의 풀이

import java.util.Arrays;

class Solution {
  public int[] solution(int[] arr, int divisor) {
          int[] answer = Arrays.stream(arr).filter(factor -> factor % divisor == 0).toArray();
          if(answer.length == 0) answer = new int[] {-1};
          Arrays.sort(answer);
          return answer;
  }
}

  • stream은 역시 시간이 오래 걸리지만, 간단하게 해결할 수 있다는 장점이 있다.
  • 나는 정확히 몇 개의 값이 들어갈지 모르기 때문에 크기가 넉넉한 result 배열과 크기가 고정된 answer 배열을 모두 선언했어야 했다. stream을 쓰는 경우에는 내가 했던 방법처럼 귀찮게 여러 개 생성할 이유는 없어질 것이다.

0개의 댓글