-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathRotationArray.java
More file actions
49 lines (37 loc) · 1.08 KB
/
Copy pathRotationArray.java
File metadata and controls
49 lines (37 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package algo_lib;
public class RotationArray {
public int[] rightRotation1D(int[] input, int k) {
if (input == null || input.length <= 0)
return input;
final int length = input.length;
k %= length;
int index = length-k;
int[] result = new int[length];
for (int i = 0; i < length; ++i) {
if (index >= length) {
index -= length;
}
result[i] = input[index];
++index;
}
return result;
}
public int[][] rightRotation2D(int[][] mat, int k) {
if (mat == null) return mat;
for (int i = 0; i < k; ++i) {
mat = rightRotation2D(mat);
}
return mat;
}
private int[][] rightRotation2D(int[][] mat) {
final int M = mat.length;
final int N = mat[0].length;
int[][] rotatedMat = new int[N][M];
for (int r = 0; r < M; r++) {
for (int c = 0; c < N; c++) {
rotatedMat[c][M-1-r] = mat[r][c];
}
}
return rotatedMat;
}
}