Given an array of integers `nums`, sort the array in ascending order.

Example 1:

  1. Input: [5,2,3,1]
  2. Output: [1,2,3,5]

Example 2:

  1. Input: [5,1,1,2,0,0]
  2. Output: [0,0,1,1,2,5]

Note:

  1. 1 <= A.length <= 10000
  2. -50000 <= A[i] <= 50000

这道题让我们给数组排序,在平时刷其他题的时候,遇到要排序的时候,一般都会调用系统自带的排序函数,像 C++ 中直接就调用 sort 函数即可,但是这道题考察的就是排序,再调用系统的排序函数就有些说不过去了。这里需要自己实现排序功能,常见排序方法有很多,插入排序,选择排序,堆排序,快速排序,冒泡排序,归并排序,桶排序等等。它们的时间复杂度不尽相同,这道题貌似对于平方级复杂度的排序方法会超时,所以只能使用那些速度比较快的排序方法啦。题目给定了每个数字的范围是 [-50000, 50000],并不是特别大,这里可以使用记数排序 Count Sort,在 LeetCode 中也有直接利用这个解法的题[Sort Colors](http://www.cnblogs.com/grandyang/p/4341243.html),建立一个大小为 100001 的数组 count,然后统计 nums 中每个数字出现的个数,然后再从0遍历到 100000,对于每个遍历到的数字i,若个数不为0,则加入 count 数组中对应个数的 i-50000 到结果数组中,这里的 50000 是 offset,因为数组下标不能为负数,在开始统计个数的时候,每个数字都加上了 50000,那么最后组成有序数组的时候就要减去,参见代码如下:


解法一:

  1. class Solution {
  2. public:
  3. vector<int> sortArray(vector<int>& nums) {
  4. int n = nums.size(), j = 0;
  5. vector<int> res(n), count(100001);
  6. for (int num : nums) ++count[num + 50000];
  7. for (int i = 0; i < count.size(); ++i) {
  8. while (count[i]-- > 0) {
  9. res[j++] = i - 50000;
  10. }
  11. }
  12. return res;
  13. }
  14. };

下面就是大名鼎鼎的快速排序了 Quick Sort,貌似 STL 中的内置 sort 函数就是基于快速排序的,只不过这里要自己写而已。在 LeetCode 中也有一道使用这个算法思想的题 [Kth Largest Element in an Array](http://www.cnblogs.com/grandyang/p/4539757.html)。快排的精髓在于选一个 pivot,然后将所有小于 pivot 的数字都放在左边,大于 pivot 的数字都放在右边,等于的话放哪边都行。但是此时左右两边的数组各自都不一定是有序的,需要再各自调用相同的递归,直到细分到只有1个数字的时候,再返回的时候就都是有序的了,参见代码如下:


解法二:

  1. class Solution {
  2. public:
  3. vector<int> sortArray(vector<int>& nums) {
  4. quickSort(nums, 0, (int)nums.size() - 1);
  5. return nums;
  6. }
  7. void quickSort(vector<int>& nums, int start, int end) {
  8. if (start >= end) return;
  9. int pivot = nums[start], i = start + 1, j = end;
  10. while (i <= j) {
  11. if (nums[i] > pivot && nums[j] < pivot) {
  12. swap(nums[i++], nums[j--]);
  13. }
  14. if (nums[i] <= pivot) ++i;
  15. if (nums[j] >= pivot) --j;
  16. }
  17. swap(nums[start], nums[j]);
  18. quickSort(nums, start, j - 1);
  19. quickSort(nums, j + 1, end);
  20. }
  21. };

我们也可以使用混合排序 Merge Sort,在 LeetCode 中也有一道使用这个思想的题 [Count of Range Sum](http://www.cnblogs.com/grandyang/p/5162678.html)。混合排序的思想跟快速排序比较类似,但也不完全一样,这里其实是一种先对半分,一直不停的对半分,直到分到只有一个数字的时候返回,然后在返回的途中进行合并,合并的时候用到了一个临时数组 tmp,先将区间 [start, end] 中的数字按顺序存入这个临时数组 tmp 中,然后再覆盖原数组中的对应位置即可,参见代码如下:


解法三:

  1. class Solution {
  2. public:
  3. vector<int> sortArray(vector<int>& nums) {
  4. mergeSort(nums, 0, (int)nums.size() - 1);
  5. return nums;
  6. }
  7. void mergeSort(vector<int>& nums, int start, int end) {
  8. if (start >= end) return;
  9. int mid = (start + end) / 2;
  10. mergeSort(nums, start, mid);
  11. mergeSort(nums, mid + 1, end);
  12. merge(nums, start, mid, end);
  13. }
  14. void merge(vector<int>& nums, int start, int mid, int end) {
  15. vector<int> tmp(end - start + 1);
  16. int i = start, j = mid + 1, k = 0;
  17. while (i <= mid && j <= end) {
  18. if (nums[i] < nums[j]) tmp[k++] = nums[i++];
  19. else tmp[k++] = nums[j++];
  20. }
  21. while (i <= mid) tmp[k++] = nums[i++];
  22. while (j <= end) tmp[k++] = nums[j++];
  23. for (int idx = 0; idx < tmp.size(); ++idx) {
  24. nums[idx + start] = tmp[idx];
  25. }
  26. }
  27. };

Github 同步地址:

https://github.com/grandyang/leetcode/issues/912

类似题目:

Kth Largest Element in an Array

Sort Colors

Count of Range Sum

参考资料:

https://leetcode.com/problems/sort-an-array/

https://leetcode.com/problems/sort-an-array/discuss/319326/Java-merge-sort-implementation

https://leetcode.com/problems/sort-an-array/discuss/293820/Easiest-and-fastest-solution.-O(10n)

https://leetcode.com/problems/sort-an-array/discuss/280903/C%2B%2B-QuickSort-and-CountingSort-solutions

[LeetCode All in One 题目讲解汇总(持续更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)

[LeetCode] 912. Sort an Array 数组排序的更多相关文章

  1. Leetcode 912. Sort an Array

    class Solution: def sortArray(self, nums: List[int]) -> List[int]: return sorted(nums)

  2. 【LeetCode】912. Sort an Array 解题报告(C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 库函数排序 桶排序 红黑树排序 归并排序 快速排序 ...

  3. 【leetcode】912. Sort an Array

    题目如下: Given an array of integers nums, sort the array in ascending order. Example 1: Input: [5,2,3,1 ...

  4. LeetCode 360. Sort Transformed Array

    原题链接在这里:https://leetcode.com/problems/sort-transformed-array/description/ 题目: Given a sorted array o ...

  5. [LeetCode] 360. Sort Transformed Array 排序转换后的数组

    Given a sorted array of integers nums and integer values a, b and c. Apply a function of the form f( ...

  6. LeetCode 912. 排序数组(Sort an Array) 43

    912. 排序数组 912. Sort an Array 题目描述 每日一算法2019/6/15Day 43LeetCode912. Sort an Array

  7. [CareerCup] 11.2 Sort Anagrams Array 异位词数组排序

    11.2 Write a method to sort an array of strings so that all the anagrams are next to each other. 这道题 ...

  8. #Leetcode# 922. Sort Array By Parity II

    https://leetcode.com/problems/sort-array-by-parity-ii/ Given an array A of non-negative integers, ha ...

  9. [LeetCode] 922. Sort Array By Parity II 按奇偶排序数组之二

    Given an array A of non-negative integers, half of the integers in A are odd, and half of the intege ...

随机推荐

  1. 此贴告诉你:为啥shell脚本人,不建议学python

    py很强大,我承认.但在运维方面,py不但不强大,还有硬伤.正因为有下述硬伤,所以我们运维,还是用shell多,用py极少.我看到用shell的人很多,你建议人用python,人说py是很好,但下一秒 ...

  2. 【Oracle】rman基于时间点恢复

    rman基于时间点恢复 场景: 由于某研究的误操作,导致财务模块的数据丢失,如何使用rman基于时间点恢复数据. 思路 1.克隆数据库的虚拟机,直接对数据库的数据进行恢复 RMAN> shutd ...

  3. layui + mvc + ajax 导出Excel功能

    为了更方便,没基础的伙伴更容易理解,我尽量详细简便 省了很多代码,一步一步的试 自己引入文件 1. html 前端视图代码 Layui的数据绑定 全部代码 @{ Layout = null; } &l ...

  4. word转html预览

    #region Index页面 /// <summary> /// Index页面 /// </summary> /// <paramname="url&quo ...

  5. 纯C语言实现顺序队列

    #include <stdio.h> #include <stdlib.h> #define MAXSIZE 6 typedef int QElemType; typedef ...

  6. Lambda(二)lambda表达式使用

    Lambda(二)lambda表达式使用 Lambda 表达式组成: /* param list arrow lambda body (o1,o2) -> o1.getColor().Compa ...

  7. JZOJ 2158. 蚂蚁

    这个是今天早上比赛的内容,比较水给大伙们讲一下(我只会这一个) 题目大意: n只蚂蚁以每秒1cm的速度在长为L  cm(厘米,不是lcm)的竿子上爬行.当蚂蚁爬到竿子的端点时就会掉落.由于竿子太细,两 ...

  8. vue学习指南:第四篇(详细) - vue的 :class 和 :style

    1. :class = “a” 说明 vue 中有个叫 a 的属性 这个标签的class 就是 a的值 2. :class = “{ active:isactive }” Active的存在取决于 i ...

  9. SQL中的视图(极客时间)

    视图 视图也就是虚拟表, 本身不具备数据, 是SQL中的一个变红要概念. 如图 视图可以帮助我们使用表的一部分, 而不是所有的表, 另一方面可以针对不同的用户制定不同的查询视图. 创建, 更新与删除视 ...

  10. 用Random产生1到10之间的一个随机数

    bat中怎样用Random产生1到10之间的一个随机数? 当然是用%random%,示例: @echo off rem 用Random产生1到10之间的一个随机数 set num=%random% s ...