배열 뒤집기
정수가 들어 있는 배열 num_list가 매개변수로 주어집니다. num_list의 원소의 순서를 거꾸로 뒤집은 배열을 return하도록 solution 함수를 완성해주세요.
my_string은 소문자와 공백으로 이루어져 있습니다.
1 ≤ my_string의 길이 ≤ 1,000
💻 풀이
replaceAll() 을 사용해 모음을 없애준다.⌛ 시간 0.01ms ~ 0.02ms
public int[] solution(int[] num_list) {
int[] num = new int[num_list.length];
for(int i = 0; i < num_list.length; i++) {
num[i] = num_list[num_list.length - i - 1];
}
return num;
}
💻 풀이
, 로 구분하면 1개 이상의 조건을 설정할 수 있다.⌛ 시간 0.20ms ~ 0.29ms
public int[] solution1_1(int[] num_list) {
int[] num = new int[num_list.length];
for(int i = num_list.length -1, j = 0; i >= 0; i--, j++) {
num[j] = num_list[i];
}
return num;
}
💻 풀이
Collection.reverse 는 List 에서 사용 가능하기 때문에 List<Integer> 로 list를 만들어준다.boxed() 를 사용해 오토박싱 을 해준다.collect(Collectors.toList()) 를 통해 스트림을 list로 변환해준다.List<Integer> list = Arrays.stream(num_list).boxed().collect(Collectors.toList());
Collections.reverse(list);
stream()mapToint(Integer::intValue) 를 사용해 Integer 객체해서 int로 언박싱을 해준다.:: : 매서드 레퍼런스 문법으로 만약 사용하지 않을 경우 map(x -> xlntValue()) 로 사용해 줄 수 있다.toArray()를 사용해준다.return list.stream().mapToInt(Integer::intValue).toArray();
⌛ 시간 2.97ms ~ 4.42ms
전체코드
public int[] solution2(int[] num_list) {
List<Integer> list = Arrays.stream(num_list).boxed().collect(Collectors.toList());
Collections.reverse(list);
return list.stream().mapToInt(Integer::intValue).toArray();
}