File tree Expand file tree Collapse file tree 2 files changed +51
-0
lines changed Expand file tree Collapse file tree 2 files changed +51
-0
lines changed Original file line number Diff line number Diff line change 1+ all :
2+ gcc -O2 -o test rotate_array.c
Original file line number Diff line number Diff line change 1+ #include <stdio.h>
2+ #include <stdlib.h>
3+
4+ static void reverse (int * nums , int lo , int hi )
5+ {
6+ while (lo < hi ) {
7+ int tmp = nums [lo ];
8+ nums [lo ] = nums [hi ];
9+ nums [hi ] = tmp ;
10+ lo ++ ;
11+ hi -- ;
12+ }
13+ }
14+
15+ static void rotate (int * nums , int numsSize , int k )
16+ {
17+ k %= numsSize ;
18+ if (k == 0 ) {
19+ return ;
20+ }
21+
22+ reverse (nums , 0 , numsSize - 1 - k );
23+ reverse (nums , numsSize - k , numsSize - 1 );
24+ reverse (nums , 0 , numsSize - 1 );
25+ }
26+
27+ int main (int argc , char * * argv )
28+ {
29+ if (argc < 2 ) {
30+ fprintf (stderr , "Usage: ./test k n1 n2...\n" );
31+ exit (-1 );
32+ }
33+
34+ int k = atoi (argv [1 ]);
35+ int i , count = argc - 2 ;
36+ int * nums = malloc (count * sizeof (int ));
37+ for (i = 0 ; i < count ; i ++ ) {
38+ nums [i ] = atoi (argv [i + 2 ]);
39+ }
40+
41+ rotate (nums , count , k );
42+
43+ for (i = 0 ; i < count ; i ++ ) {
44+ printf ("%d " , nums [i ]);
45+ }
46+ printf ("\n" );
47+
48+ return 0 ;
49+ }
You can’t perform that action at this time.
0 commit comments