Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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
- 알고리즘
- 항해99
- programmers
- 리액트
- Algorithm
- redux-toolkit
- 매일메일
- createSlice
- maeil-mail
- SW
- java
- redux
- Get
- 이코테
- JavaScript
- Python
- react-redux
- 프로그래머스
- 테코테코
- 자바
- sw expert academy
- 코딩테스트합격자되기
- C++
- redux-saga
- useDispatch
- react-router
- 항해플러스
- react
- axios
- json-server
Archives
- Today
- Total
Binary Journey
[프로그래머스] 나누어 떨어지는 숫자 배열 본문
반응형
출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges
** Javascript
1)
처음 제출한 풀이
function solution(arr, divisor) {
var answer = arr.filter((item) => item % divisor === 0).sort((a, b) => a - b);
return answer.length > 0 ? answer : [-1];
}
2)
reduce 이용한 풀이
1번이 더 나은 듯
function solution(arr, divisor) {
let answer = arr.reduce((acc, curr) => {
if (curr % divisor === 0) acc.push(curr);
return acc;
}, []).sort((a, b) => a - b);
return answer.length ? answer : [-1];
}
* 더 빠르게 하려면 sort를 return 절 안에 넣는 게 낫다.
** Java
import java.util.*;
class Solution {
public int[] solution(int[] arr, int divisor) {
int[] answer = Arrays.stream(arr).filter(x -> x % divisor == 0).toArray();
Arrays.sort(answer);
return answer.length > 0 ? answer : new int[] {-1};
}
}
** Python
def solution(arr, divisor):
answer = [i for i in arr if i % divisor == 0]
return sorted(answer) if len(answer) > 0 else [-1]
반응형
'프로그래머스 > level 1' 카테고리의 다른 글
[프로그래머스] 가운데 글자 가져오기 (0) | 2021.09.30 |
---|---|
[프로그래머스] 같은 숫자는 싫어 (0) | 2021.09.23 |
[프로그래머스] 두 정수 사이의 합 (0) | 2021.09.23 |
[프로그래머스] 다트게임 (0) | 2021.09.15 |
[프로그래머스][위클리챌린지] 6주차 복서 정렬하기 (0) | 2021.09.12 |