1515 */
1616public class ArrayRotation {
1717
18- private ArrayRotation () {
19- }
18+ private ArrayRotation () {
19+ }
2020
21- /**
22- * Rotates the array to the right by k positions.
23- *
24- * @param nums the input array
25- * @param k number of rotations
26- */
27- public static void rotateRight (int [] nums , int k ) {
21+ /**
22+ * Rotates the array to the right by k positions.
23+ *
24+ * @param nums the input array
25+ * @param k number of rotations
26+ */
27+ public static void rotateRight (int [] nums , int k ) {
2828
29- int n = nums .length ;
29+ int n = nums .length ;
3030
31- if (n == 0 ) {
32- return ;
33- }
31+ if (n == 0 ) {
32+ return ;
33+ }
3434
35- k = k % n ;
35+ k = k % n ;
3636
37- reverse (nums , 0 , n - 1 );
38- reverse (nums , 0 , k - 1 );
39- reverse (nums , k , n - 1 );
40- }
37+ reverse (nums , 0 , n - 1 );
38+ reverse (nums , 0 , k - 1 );
39+ reverse (nums , k , n - 1 );
40+ }
4141
42- /**
43- * Rotates the array to the left by k positions.
44- *
45- * @param nums the input array
46- * @param k number of rotations
47- */
48- public static void rotateLeft (int [] nums , int k ) {
42+ /**
43+ * Rotates the array to the left by k positions.
44+ *
45+ * @param nums the input array
46+ * @param k number of rotations
47+ */
48+ public static void rotateLeft (int [] nums , int k ) {
4949
50- int n = nums .length ;
50+ int n = nums .length ;
5151
52- if (n == 0 ) {
53- return ;
54- }
52+ if (n == 0 ) {
53+ return ;
54+ }
5555
56- k = k % n ;
56+ k = k % n ;
5757
58- reverse (nums , 0 , k - 1 );
59- reverse (nums , k , n - 1 );
60- reverse (nums , 0 , n - 1 );
61- }
58+ reverse (nums , 0 , k - 1 );
59+ reverse (nums , k , n - 1 );
60+ reverse (nums , 0 , n - 1 );
61+ }
6262
63- /**
64- * Reverses elements between start and end indices.
65- *
66- * @param nums the input array
67- * @param start starting index
68- * @param end ending index
69- */
70- private static void reverse (int [] nums , int start , int end ) {
63+ /**
64+ * Reverses elements between start and end indices.
65+ *
66+ * @param nums the input array
67+ * @param start starting index
68+ * @param end ending index
69+ */
70+ private static void reverse (int [] nums , int start , int end ) {
7171
72- while (start < end ) {
72+ while (start < end ) {
7373
74- int temp = nums [start ];
75- nums [start ] = nums [end ];
76- nums [end ] = temp ;
74+ int temp = nums [start ];
75+ nums [start ] = nums [end ];
76+ nums [end ] = temp ;
7777
78- start ++;
79- end --;
78+ start ++;
79+ end --;
80+ }
8081 }
81- }
8282}
0 commit comments