Rotate Array

来源:互联网 发布:ecshop微商城源码下载 编辑:程序博客网 时间:2024/05/23 13:35
Question: Rotate an array of n elements to the right by k steps.旋转一个含n个元素的数组, 从数组最后一个元素向前算起的第k个元素开始.

For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]

Solution: Requirement: do this problem in O(1) space and in O(n) time.

Step1: Split array into two parts: Before given number and after given number: 

Before number: (Array, 0, Array.length - order - 1); After number: (Array, Array.length - order, Array.length - 1);

[1,2,3,4,5,6,7] --> [1,2,3,4,|5,6,7]

Step2: Reverse the two lists

[4,3,2,1,|7,6,5]

Step3: Reverse the whole list

[5,6,7,1,3,3,4]


public void rotate(int[] array, int order) {
if(array == null || order < 0){
throw new IllegalArgumentException("Illegal input");
}

reverse(array, 0, array.length - order - 1);
reverse(array, array.length - order, array.length-1);
reverse(array, 0, array.length - 1);

}

private void reverse(int[] array, int start, int end){
while(start < end){
int temp = array[start];
array[start] = array[end];
array[end] = temp;
start++;
end--;
}
}

0 0
原创粉丝点击