发信人: swanswan (swan), 信区: JobHunting
标 题: Rotating an array in place
发信站: BBS 未名空间站 (Thu Mar 29 02:00:55 2012, 美东)
0 1 2 3 4 5 6 7 (N=8, k=3)
->
3 4 5 6 7 0 1 2
leetcode上那个要移动2N次,写了个只要移动N次的
标 题: Rotating an array in place
发信站: BBS 未名空间站 (Thu Mar 29 02:00:55 2012, 美东)
0 1 2 3 4 5 6 7 (N=8, k=3)
->
3 4 5 6 7 0 1 2
leetcode上那个要移动2N次,写了个只要移动N次的
#include <stdio.h>
void rotate(int* a, int N, int k)
{
if (N<=1) return;
if (k>N) k=k%N;
if (k==0) return;
int moved = 0;
for (int i=0; moved<N; i++) {
int tmp = a[i];
int current = i;
do {
moved++;
int next = (current+k)%N;
if (next == i) {
a[current] = tmp;
break;
} else {
a[current] = a[next];
current = next;
}
} while (1);
}
}
int main()
{
int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
rotate(a, 10, 7);
for (int i=0; i<10; i++) printf("%d ", a[i]);
}
comments by winhao
就是按照每次k步的跳去 copy,会形成一个环,
如果还没有把所有的copy完,然后开始下一个环,直到拷贝了N次。
comments by peking2 : 注意k可以为负数
== > solution by longway2008
if ( k<0 )
k += N;