1차원 배열 회전하기
/**
* Rotate 1-dimensional Array
* Time complexity: O(n)
* Space complexity: O(1)
* */
public class Rotate {
private static final Logger logger = Logger.getLogger(Rotate.class.getName());
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int len = nums.length;
int k = 12 % len;
/* rotate right */
rotate(nums, 0, k-1, len-1);
logger.info("rotated right: " + Arrays.toString(nums));
/* rotate left */
rotate(nums, 0, len-k-1, len-1);
logger.info("rotated left: " + Arrays.toString(nums));
}
private static void rotate(int[] nums, int left, int mid, int right) {
reverse(nums, left, right);
reverse(nums, left, mid);
reverse(nums, mid+1, right);
}
private static void reverse(int[] nums, int left, int right) {
while(right > left) {
int tmp = nums[right];
nums[right--] = nums[left];
nums[left++] = tmp;
}
}
}