-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDivide_arrays_to_array.java
More file actions
43 lines (35 loc) · 932 Bytes
/
Copy pathDivide_arrays_to_array.java
File metadata and controls
43 lines (35 loc) · 932 Bytes
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
class Solution {
public int[][] divideArray(int[] nums, int k) {
if (nums.length % 3 != 0) {
return new int[0][0];
}
int size = nums.length;
int max = 0;
for (int n : nums) {
max = Math.max(max, n);
}
int[] freqs = new int[max + 1];
for (int n : nums) {
++freqs[n];
}
int[][] subs = new int[size / 3][3];
for (int n = 1, r = 0, c = 0; r < subs.length && n <= max;) {
if (freqs[n] == 0) {
++n;
}
else if (c == subs[r].length) {
++r;
c = 0;
}
else if (c == 0 || n - subs[r][0] <= k) {
subs[r][c] = n;
--freqs[n];
++c;
}
else {
return new int[0][0];
}
}
return subs;
}
}