Java实现 LeetCode 912 排序数组(用数组去代替排序O(N))
912. 排序数组
给你一个整数数组 nums,将该数组升序排列。
示例 1:
输入:nums = [5,2,3,1]
输出:[1,2,3,5]
示例 2:
输入:nums = [5,1,1,2,0,0]
输出:[0,0,1,1,2,5]
提示:
1 <= nums.length <= 50000
-50000 <= nums[i] <= 50000
PS:
还记得当时这个排序,看的我一脸蒙蔽,为啥会这么快
class Solution {
public int[] sortArray(int[] nums) {
int max = -50001, min = 50001;
for (int num: nums) {
max = Math.max(num, max);
min = Math.min(num, min);
}
int[] counter = new int[max - min + 1];
for (int num: nums) {
counter[num - min]++;
}
int idx = 0;
for (int num = min; num <= max; num++) {
int cnt = counter[num - min];
while (cnt-- > 0) {
nums[idx++] = num;
}
}
return nums;
}
}