Skip to content

Commit a1a91da

Browse files
Create 912. 计数排序.md
1 parent 0f4da09 commit a1a91da

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

Sort/912. 计数排序.md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
#### 912. 排序数组
2+
3+
难度:中等
4+
5+
---
6+
7+
给你一个整数数组 `nums`,请你将该数组升序排列。
8+
9+
**示例 1:**
10+
11+
```
12+
输入:nums = [5,2,3,1]
13+
输出:[1,2,3,5]
14+
```
15+
16+
**示例 2:**
17+
18+
```
19+
输入:nums = [5,1,1,2,0,0]
20+
输出:[0,0,1,1,2,5]
21+
```
22+
23+
**提示:**
24+
25+
* `1 <= nums.length <= 5 * 10^4`
26+
* `-5 * 10^4 <= nums[i] <= 5 * 10^4`
27+
28+
---
29+
30+
计数排序:
31+
32+
最后的 `while` 循环并不需要判断 `index` 是否越界,因为 `array` 数组总是以 `1` 结尾,并且 `i == nums.length - 1` 时,`index = maxn - minn` 并且 `array[index] = 1`,执行 `array[index]--` 后,恰好退出 `for` 循环,因此 `array[index]--` 也不需要越界检查。
33+
34+
```java
35+
class Solution {
36+
public int[] sortArray(int[] nums) {
37+
int maxn = Integer.MIN_VALUE, minn = Integer.MAX_VALUE;
38+
for(int i = 0; i < nums.length; i++){
39+
maxn = Math.max(maxn, nums[i]);
40+
minn = Math.min(minn, nums[i]);
41+
}
42+
int[] array = new int[maxn - minn + 1];
43+
for(int i = 0; i < nums.length; i++){
44+
array[nums[i] - minn]++;
45+
}
46+
int index = 0;
47+
for(int i = 0; i < nums.length; i++){
48+
while(array[index] == 0) index++;
49+
nums[i] = minn + index;
50+
array[index]--;
51+
}
52+
return nums;
53+
}
54+
}
55+
```
56+

0 commit comments

Comments
 (0)