Skip to content

Commit ca83519

Browse files
committed
Sort an Array: Add
1 parent dee9cc4 commit ca83519

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package leetcode.medium.page10;
2+
3+
public class SortAnArray {
4+
public int[] sortArray(int[] nums) {
5+
int min = Integer.MAX_VALUE;
6+
int max = Integer.MIN_VALUE;
7+
for (int num : nums) {
8+
if (num < min) {
9+
min = num;
10+
}
11+
if (num > max) {
12+
max = num;
13+
}
14+
}
15+
16+
int length = nums.length;
17+
int bucketSize = (max - min) / length;
18+
int bucketNum = (max - min) / bucketSize + 1;
19+
int[][] bucket = new int[bucketNum][bucketSize];
20+
boolean[][] store = new boolean[bucketNum][bucketSize];
21+
22+
for (int num : nums) {
23+
int i = (num - min) / bucketSize;
24+
int j = (num - min) % bucketSize;
25+
bucket[i][j] = num;
26+
store[i][j] = true;
27+
}
28+
29+
int[] sortedArray = new int[length];
30+
int k = 0;
31+
for (int i = 0; i < bucketNum; i++) {
32+
for (int j = 0; j < bucketSize; j++) {
33+
if (store[i][j]) {
34+
sortedArray[k++] = bucket[i][j];
35+
}
36+
}
37+
}
38+
39+
return sortedArray;
40+
}
41+
}

0 commit comments

Comments
 (0)