Rotate Array
배열 회전
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
정수 배열이 주어지면 nums배열을 단계적으로 오른쪽으로 회전합니다 k. 여기서 k는 음수가 아닙니다.
예시 1:
입력: nums = [1,2,3,4,5,6,7], k = 3
출력: [5,6,7,1,2,3,4]
설명:
오른쪽으로 1단계 회전: [ 7,1,2,3,4,5,6]
오른쪽으로 2단계 회전: [6,7,1,2,3,4,5]
오른쪽으로 3단계 회전: [5,6,7, 1,2,3,4]
예 2:
입력: nums = [-1,-100,3,99], k = 2
출력: [3,99,-1,-100]
설명:
오른쪽으로 1단계 회전: [99,-1,-100, 3]
오른쪽으로 2단계 회전: [3,99,-1,-100]
제약:
- 1 <= nums.length <= 105
- -231 <= nums[i] <= 231 - 1
- 0 <= k <= 105
1.첫번째 시도
public void rotate(int[] nums, int k) {
int[] temp = new int[nums.length];
int idx = 0;
for(int i = nums.length-k ; i< nums.length ; i++){
//에러지점
temp[idx++] = nums[i];
}
int idx2 = 0;
for(int i = 0 ; i < temp.length ; i++){
if(i >= k ){
temp[i] = nums[idx2++];
}
}
for(int i = 0 ; i < nums.length ; i++){
nums[i] = temp[i];
}
}
배열의 num.length - k 번째부터 끝까지 배열을 순회하여 값을 temp배열에 넣어둔다
temp배열의 나머지 부분은 num[idx2++]로 채워 넣는다.
마지막에 temp 배열의 수를 num배열로 옮긴다.
하지만
[-1], k=2 의 테스트에서는 java.lang.ArrayIndexOutOfBoundsException 에러가 생겨 실패했다.
에러지점 i = nums.length-k는 즉, 1-2가 되고 값은 -1이 되는데 num[-1]이 되기때문에 배열의 범위를 벗어 났기 떄문이다.
2.두번째 시도
public void rotate(int[] nums, int k) {
int[] temp = new int[nums.length];
int idx = 0;
try{
for(int i = nums.length-k ; i< nums.length ; i++){
temp[idx++] = nums[i];
}
int idx2 = 0;
for(int i = 0 ; i < temp.length ; i++){
if(i >= k ){
temp[i] = nums[idx2++];
}
}
for(int i = 0 ; i < nums.length ; i++){
nums[i] = temp[i];
}
}catch(Exception e){
}
}
첫번째 시도의 에러조건은 즉 회전할 수 없다고 판단하였고 try-catch를 사용하여 java.lang.ArrayIndexOutOfBoundsException 발생하면 nums 배열은 그대로 유지하도록 하였다.
하지만
[1,2], k=3의 값에서 통과하지 못하였다.
3.세번째 시도(성공)
public void rotate(int[] nums, int k) {
int[] temp = new int[nums.length];
int idx = k%nums.length;
int idx2 = idx;
for(int i=0; i<idx; i++) {
temp[i] = nums[temp.length-idx+i];
}
for(int i=0; i<nums.length-idx; i++) {
temp[idx2++] = nums[i];
}
for(int i=0; i<nums.length; i++) {
nums[i] = temp[i];
}
}
idx는 우측으로 이동할 수를 k%num.length로 구하였다
temp 배열의 이동할 수의 값을 채워 넣었다.
temp 배열의 값이 없는 부분부터 nums[i]로 채워넣었다
마지막에 temp배열을 nums배열로 옮겨 마무리했다.