LeetCode 189

Rotate Array

Rotate an array of n elements to the right by k steps.

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].

1 2 7 4 5 6 3
1 6 7 4 5 2 3
5 6 7 4 1 2 3

Note:
Try to come up as many solutions as you can,
there are at least 3 different ways to solve this problem.

[show hint]

Related problem: Reverse Words in a String II

 

 1 /*************************************************************************
 2     > File Name: LeetCode189.c
 3     > Author: Juntaran
 4     > Mail: Juntaranmail@gmail.com
 5     > Created Time: Tue 13 May 2016 16:27:23 PM CST
 6  ************************************************************************/
 7 
 8 /*************************************************************************
 9 
10     Rotate Array
11 
12     Rotate an array of n elements to the right by k steps.
13 
14     For example, with n = 7 and k = 3,
15     the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
16 
17     1 2 7 4 5 6 3
18     1 6 7 4 5 2 3
19     5 6 7 4 1 2 3
20 
21     Note:
22     Try to come up as many solutions as you can,
23     there are at least 3 different ways to solve this problem.
24 
25     [show hint]
26 
27     Related problem: Reverse Words in a String II
28 
29  ************************************************************************/
30 
31 #include <stdio.h>
32 
33 void printNums( int* nums, int numsSize )
34 {
35     int i;
36     for( i=0; i<numsSize; i++ )
37     {
38         printf("%d ",nums[i]);
39     }
40     printf("\n");
41 }
42 
43 void rotate(int* nums, int numsSize, int k)
44 {
45     k = k % numsSize;
46     if(k == 0)
47     {
48         return;
49     }
50     int temp = 0;
51     int left = 0;
52     int right = numsSize-k;
53     int n = numsSize - 1;
54     while( n > 0 )
55     {
56         if( left == right )
57         {
58             right ++;
59             left = right + k - numsSize;
60             n --;
61         }
62         
63         temp = nums[right];
64         nums[right] = nums[left];
65         nums[left] = temp;
66         left = (left + k) %  numsSize;
67         
68         n --;
69         
70 //        printNums( nums, numsSize );
71     }
72 }
73 
74 void rotate2(int* nums, int numsSize, int k)
75 {
76     while( k > 0 )
77     {
78         int temp = nums[numsSize-1];
79         int i;
80         for( i=numsSize-1; i>0; i-- )
81         {
82             nums[i] = nums[i-1];
83 //            printNums( nums, numsSize );
84         }
85         nums[0] = temp;
86         k--;
87 //        printNums( nums, numsSize );
88     }
89 }
90 
91 int main()
92 {
93     int nums[] = {1,2,3,4,5,6};
94     int numsSize = 6;
95     int k = 2;
96     rotate2( nums, numsSize, k );
97 
98     return 0;
99 }

 

posted @ 2016-05-20 12:51  Juntaran  阅读(116)  评论(0编辑  收藏  举报