1+ package com .leetcode .arrays ;
2+
3+ import java .util .Arrays ;
4+
5+ /**
6+ * Problem: https://leetcode.com/problems/rotate-array/
7+ *
8+ * @author rampatra
9+ * @since 2019-04-20
10+ */
11+ public class RotateArray {
12+
13+ /**
14+ * Time complexity: O(n)
15+ * where,
16+ * n = no. of elements in the array
17+ * <p>
18+ * Runtime: <a href="https://leetcode.com/submissions/detail/224425565/">0 ms</a>.
19+ *
20+ * @param nums
21+ * @param k
22+ */
23+ public static void rotate (int [] nums , int k ) {
24+
25+ if (k > nums .length ) {
26+ k = k % nums .length ;
27+ }
28+
29+ reverse (nums , 0 , nums .length );
30+ reverse (nums , 0 , k );
31+ reverse (nums , k , nums .length );
32+ }
33+
34+ private static void reverse (int [] nums , int start , int end ) {
35+ int temp ;
36+ for (int i = start , j = end - 1 ; i < j ; i ++, j --) {
37+ temp = nums [i ];
38+ nums [i ] = nums [j ];
39+ nums [j ] = temp ;
40+ }
41+ }
42+
43+ public static void main (String [] args ) {
44+ // normal case
45+ int [] arr = {1 , 2 , 3 , 4 , 5 , 6 , 7 };
46+ System .out .println (Arrays .toString (arr ));
47+ rotate (arr , 3 );
48+ System .out .println (Arrays .toString (arr ));
49+
50+ // edge cases
51+ arr = new int []{1 , 2 };
52+ System .out .println (Arrays .toString (arr ));
53+ rotate (arr , 2 );
54+ System .out .println (Arrays .toString (arr )); // should be [1, 2]
55+
56+ arr = new int []{1 , 2 };
57+ System .out .println (Arrays .toString (arr ));
58+ rotate (arr , 3 );
59+ System .out .println (Arrays .toString (arr )); // should be [2, 1]
60+
61+ arr = new int []{1 , 2 , 3 };
62+ System .out .println (Arrays .toString (arr ));
63+ rotate (arr , 4 );
64+ System .out .println (Arrays .toString (arr )); // should be [3, 1, 2]
65+
66+ arr = new int []{1 };
67+ System .out .println (Arrays .toString (arr ));
68+ rotate (arr , 2 );
69+ System .out .println (Arrays .toString (arr ));
70+ }
71+ }
0 commit comments