문제 :
https://school.programmers.co.kr/learn/courses/30/lessons/181861
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
해결 :
import java.util.*;
class Solution {
public int[] solution(int[] arr) {
List<Integer> answer = new ArrayList<>();
int x = 0;
for(int i = 0; i<arr.length ; i++){
x = arr[i];
for(int j=0; j<x; j++){
answer.add(x);
}
}
int[] list = new int[answer.size()];
for(int i = 0; i<answer.size(); i++){
list[i] = answer.get(i);
}
return list;
}
}
다른 사람 풀이 :
import java.util.*;
import java.util.stream.Collectors;
class Solution {
public List<Integer> solution(int[] arr) {
return Arrays.stream(arr).boxed().flatMap(num -> Collections.nCopies(num, num).stream()).collect(Collectors.toList());
}
}
boxed() 메소드
IntStream 같이 원시 타입에 대한 스트림 지원을 클래스 타입으로 전환하여 실행 가능한 기능을 수행하기 위해 존재합니다.
( ex. IntStream -> Stream )
( ex. int 자체로는 Collection에 못 담기 때문에 Integer 클래스로 변환하여 List<Integer> 로 담기 위해 등 )
'알고리즘 > [프로그래머스] JAVA' 카테고리의 다른 글
[코딩 기초 트레이닝] 배열 만들기 1 (0) | 2024.01.24 |
---|---|
[코딩 기초 트레이닝] 문자 개수 세기 (0) | 2024.01.24 |
[코딩 기초 트레이닝] 첫 번째로 나오는 음수 (0) | 2024.01.23 |
[코딩 기초 트레이닝] 2의 영역 (0) | 2024.01.23 |
[코딩 기초 트레이닝] n번째 원소부터 (0) | 2024.01.23 |