Leecode912. 排序数组

简介: Leecode912. 排序数组

给你一个整数数组 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

看到这个排序题,首先一般会想到Java自带的数组排序Arrays.sort(nums)

不过如果想运行效率更高一点的话可以选用计数排序,计数排序的时间复杂度是O(n),而Arrays.sort里面的排序算法时间复杂度是O(nlogn)

第一种:内部主要是用快排

class Solution {
    public int[] sortArray(int[] nums) {
        Arrays.sort(nums);
        return nums;
    }
}

第二种:计数排序

class Solution {
    public int[] sortArray(int[] nums) {
        int max = -50000, min = 50000;
        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;
    }
}


相关文章
|
1月前
|
算法 C语言
OJ刷题:求俩个数组的交集(没学哈希表?快排双指针轻松搞定!)
OJ刷题:求俩个数组的交集(没学哈希表?快排双指针轻松搞定!)
|
5月前
快排&超详细,Leetcode排序数组题目带你升华掌握(上)
快排&超详细,Leetcode排序数组题目带你升华掌握
20 0
|
2月前
|
算法 测试技术 C语言
leecode算法题之数组
leecode算法题之数组
|
3月前
面试题 10.01:合并排序的数组
面试题 10.01:合并排序的数组
14 0
【数组】面试题 10.01. 合并排序的数组
【数组】面试题 10.01. 合并排序的数组
|
4月前
|
算法 Java
每日一题《剑指offer》数组篇之统计数字在排序数组中出现的次数
每日一题《剑指offer》数组篇之统计数字在排序数组中出现的次数
32 0
每日一题《剑指offer》数组篇之统计数字在排序数组中出现的次数
|
4月前
|
算法 搜索推荐 API
LeetCode 912. 排序数组
LeetCode 912. 排序数组
26 0
|
5月前
|
测试技术 编译器 Shell
快排&超详细,Leetcode排序数组题目带你升华掌握(下)
快排&超详细,Leetcode排序数组题目带你升华掌握(上)
53 0
|
10月前
Leecode10.01 合并排序数组
Leecode10.01 合并排序数组
43 0
|
11月前
leetcode905–按奇偶排序数组(经典/原地排序)
leetcode905–按奇偶排序数组(经典/原地排序)