[알고리즘문제풀기] 배열 뒤집기

silver's avatar
Nov 21, 2024
[알고리즘문제풀기] 배열 뒤집기
 

문제

 

내가 작성한 정답

class Solution { public int[] solution(int[] num_list) { int n = num_list.length; int[] answer = new int[n]; for (int i = 0; i < n; i++) { answer[i] = num_list[n - i - 1]; } return answer; } }
 

다른 사람들이 작성한 정답

import java.util.stream.IntStream; class Solution { public int[] solution(int[] num_list) { return IntStream.range(0, num_list.length) .map(i -> num_list[num_list.length - i - 1]) .toArray(); } }
import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.Arrays; class Solution { public int[] solution(int[] numList) { List<Integer> list = Arrays.stream(numList).boxed().collect(Collectors.toList()); Collections.reverse(list); return list.stream().mapToInt(Integer::intValue).toArray(); } }
import java.util.stream.LongStream; class Solution { public int[] solution(int[] num_list) { return LongStream.range(1, num_list.length + 1) .mapToInt(i -> num_list[(int) (num_list.length - i)]) .toArray(); } }
 
💡
LongStream은 long 타입 데이터를 다루는 스트림으로 처리 방식은 IntStream과 유사하지만, 더 큰 데이터 크기를 처리할 수 있도록 설계되었다.

주요 메서드

  • range(long startInclusive, long endExclusive)startInclusive부터 endExclusive 전까지의 연속적인 long 값 스트림 생성.
  • rangeClosed(long startInclusive, long endInclusive)끝 값을 포함한 숫자 스트림 생성.
  • of(long... values)여러 long 값을 스트림으로 변환.
  • iterate(long seed, LongUnaryOperator f)초기값과 함수로 무한 스트림 생성.
  • generate(LongSupplier s)지정된 공급자로 값 생성.
💡

boxed

boxed() 메소드는 IntStream 같이 원시 타입에 대한 스트림 지원을 클래스 타입(예: IntStream -> Stream<Integer>)으로 전환해준다.
전용으로 실행 가능한 (예를 들어 int 자체로는 Collection에 못 담기 때문에 Integer 클래스로 변환하여 List<Integer> 로 담기 위해) 기능을 수행하기 위해 존재한다.
Share article

silver