배열이 주어지면 배열을 오른쪽으로 k단계씩 회전합니다. 여기서 k는 음수가 아닙니다.
Given an array, rotate the array to the right by k steps, where k is non-negative.
https://leetcode.com/problems/rotate-array/
Example 1:
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:
Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
자바입니다.
reverse
class Solution {
public void rotate(int[] nums, int k) {
if(nums.length == 0 || k % nums.length == 0) return;
int len = nums.length;
k%=len; //nums.length>k 일 경우 방지위해
reverse(nums, 0, len-k-1);
reverse(nums, len-k, len-1);
reverse(nums, 0, len-1);
}
public void reverse(int[] nums, int start, int end){
// int tmp=0;
while(start<end){
int tmp = nums[start];
nums[start]=nums[end];
nums[end]=tmp;
start++;
end--;
}
}
}
class Solution {
public void rotate(int[] nums, int k) {
if(nums.length == 0 || k % nums.length == 0) return;
int start = 0, i = start, curNum = nums[i], count = 0;
while(count < nums.length){
i = (i + k) % nums.length;
int tmp = nums[i];
nums[i] = curNum;
if(i == start){
start++;
i = start;
curNum = nums[i];
}
else curNum = tmp;
count++;
}
}
}