1.문제
Rotate Array - LeetCode
Rotate Array - LeetCode
Can you solve this real interview question? Rotate Array - Given an integer array nums, rotate the array to the right by k steps, where k is non-negative. Example 1: Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 step
leetcode.com
2.문제설명

이 문제는 주어진 K 만큼 순회 하는 것이다.
3.소스코드
class Solution {
public void rotate(int[] nums, int k) {
Deque<Integer> deq = new ArrayDeque<>();
for(int i: nums){
deq.add(i);
}
for(int i=0; i<k; i++){
int popItem = deq.removeLast();
deq.addFirst(popItem);
}
for(int i = 0; i<nums.length; i++){
nums[i] = deq.poll();
}
}
}
4.문제해설
문제에서 뒤에 있는 요소를 앞으로 다시 전달해주는 게 핵심이다. 이 때 deque 를 활용하여 풀면 간단하게 풀 수 있다.
하지만 직접 배열을 컨트롤 하는것이 아니라 deque라는 메모리 공간을 만들어 사용하여 속도와 메모리 측면에서는 배열을 직접 컨트롤 하여 Swap을 구성하는 편이 더 빠르고 메모리 측면에서는 좋아보인다.
'Algorithm' 카테고리의 다른 글
| [leetCode 125번] Valid Palindrome (Java) (0) | 2023.08.28 |
|---|---|
| [leetCode 121] Best Time to Buy and Sell Stock (Java) (0) | 2023.08.24 |
| [leetCode 169번] Majority Element (Java) (0) | 2023.08.24 |
| [leetCode 80번] Remove Duplicates from Sorted Array II (Java) (0) | 2023.08.24 |
| [leetCode 26번] Remove Duplicates from Sorted Array (Java) (0) | 2023.08.24 |