나의 풀이
import java.util.*;
import java.util.stream.Collectors;
import static java.util.Collections.*;
class Solution {
public int[] solution(int[] numbers, String direction) {
List<Integer> list= Arrays.stream(numbers).boxed().collect(Collectors.toList());
if (direction.equals("right")) {
rotate(list, 1);
} else {
rotate(list, -1);
}
int[] answer = list.stream().mapToInt(i -> i).toArray();
return answer;
}
}
▶ Collections.rotate() 함수를 이용하였다.
▶ 양수인 경우 오른쪽으로 회전
▶ 음수인 경우 왼쪽으로 회전
다른 사람의 풀이
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
class Solution {
public int[] solution(int[] numbers, String direction) {
List<Integer> list = Arrays.stream(numbers).boxed().collect(Collectors.toList());
if (direction.equals("right")) {
list.add(0, list.get(list.size() - 1));
list.remove(list.size() - 1);
} else {
list.add(list.size(), list.get(0));
list.remove(0);
}
return list.stream().mapToInt(Integer::intValue).toArray();
}
}
▶ list.add(인덱스, 객체)
▶ list.get(인덱스) : 해당 인덱스에서 객체를 꺼낸다.
▶ list.remove(인덱스) : 해당 인덱스에 해당하는 객체를 지운다.
▶ list.add(0, list.get(list.size() - 1));
→ 리스트의 마지막 인덱스에 얻은 "객체"를 0번 인덱스에 집어넣는다.
▶ list.remove(list.size() -1); 마지막 인덱스에 해당하는 객체를 지운다.
▶ list.add(list.size(), list.get(0));
마지막 인덱스의 바로 옆 오른쪽(인덱스)에 0인덱스에 얻은 객체를 넣는다.
'프로그래머스(자바) > LV.0(자바)' 카테고리의 다른 글
숫자 찾기→문자열+숫자=문자열 (0) | 2022.11.25 |
---|---|
암호 해독- substring(), toCharArray(), char->String에 대입가능, step (0) | 2022.11.24 |
인덱스바꾸기★ 문자열→문자열배열→List swap(), join() (0) | 2022.11.24 |
주사위의 개수 → 연산의 순서에 주의하자 (괄호의 중요성) (0) | 2022.11.24 |
약수 구하기 - IntStream.rangeClosed(1, n) (0) | 2022.11.24 |