forked from lennylxx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
189.c
68 lines (59 loc) · 1.17 KB
/
189.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <stdio.h>
void rotate(int nums[], int n, int k) {
int i, j, c;
i = j = 0;
int pre = nums[i];
int t;
for(c = 0; c < n; c++) {
i = (i + k) % n;
t = nums[i];
nums[i] = pre;
pre = t;
if (i == j) {
i = ++j;
pre = nums[i];
}
}
}
/*
Cyclic group generator to do matrix transpose.
use a 1-dimension array to reprents m*n matrix.
the result is an n*m matrix.
*/
void transpose(int *matrix, int m, int n) {
int i, j, c;
i = j = 0;
int pre = matrix[0];
int t;
for (c = 0; c < m * n - 1; c++) { /* pay attention it's m*n-1 */
i = (i % n) * m + (i / n);
t = matrix[i];
matrix[i] = pre;
pre = t;
if (i == j) {
i = ++j;
pre = matrix[i];
}
}
}
void print(int nums[], int n) {
int i;
for (i = 0; i < n; i++) {
printf("%d ", nums[i]);
}
printf("\n");
}
int main()
{
int a[7] = {1, 2, 3, 4, 5, 6, 7};
int n = 7;
int k = 4;
rotate(a, n, k);
print(a, n);
int b[6] = {1, 2, 3, 4, 5, 6};
n = 6;
k = 3;
rotate(b, n, k);
print(b, n);
return 0;
}