1
1
package com .fishercoder .solutions ;
2
2
3
- import java .util .ArrayList ;
4
- import java .util .List ;
5
-
6
3
/**
7
4
* 189. Rotate Array
8
5
@@ -33,9 +30,10 @@ public class _189 {
33
30
34
31
public static class Solution1 {
35
32
/**
33
+ * using an extra array of the same size to copy it
36
34
* O(n) space
37
35
* O(n) time
38
- * * /
36
+ */
39
37
public void rotate (int [] nums , int k ) {
40
38
int len = nums .length ;
41
39
int [] tmp = new int [len ];
@@ -52,7 +50,7 @@ public static class Solution2 {
52
50
/**
53
51
* O(1) space
54
52
* O(n) time
55
- * * /
53
+ */
56
54
public void rotate (int [] nums , int k ) {
57
55
int tmp ;
58
56
for (int i = 0 ; i < k ; i ++) {
@@ -64,38 +62,4 @@ public void rotate(int[] nums, int k) {
64
62
}
65
63
}
66
64
}
67
-
68
- public static class Solution3 {
69
- /**
70
- * My original idea and got AC'ed.
71
- * One thing to notice is that when k > nums.length, we'll continue to rotate the array, it just becomes k -= nums.length
72
- */
73
- public static void rotate (int [] nums , int k ) {
74
- if (k == 0 || k == nums .length ) {
75
- return ;
76
- }
77
- if (k > nums .length ) {
78
- k -= nums .length ;
79
- }
80
- List <Integer > tmp = new ArrayList ();
81
- int i = 0 ;
82
- if (nums .length - k >= 0 ) {
83
- i = nums .length - k ;
84
- for (; i < nums .length ; i ++) {
85
- tmp .add (nums [i ]);
86
- }
87
- } else {
88
- i = nums .length - 1 ;
89
- for (; i >= 0 ; i --) {
90
- tmp .add (nums [i ]);
91
- }
92
- }
93
- for (i = 0 ; i < nums .length - k ; i ++) {
94
- tmp .add (nums [i ]);
95
- }
96
- for (i = 0 ; i < tmp .size (); i ++) {
97
- nums [i ] = tmp .get (i );
98
- }
99
- }
100
- }
101
- }
65
+ }
0 commit comments