美文网首页
143. Sort Colors II

143. Sort Colors II

作者: 鸭蛋蛋_8441 | 来源:发表于2019-06-19 10:50 被阅读0次

Description

Given an array of n objects with k different colors (numbered from 1 to k), sort them so that objects of the same color are adjacent, with the colors in the order 1, 2, ... k.

You are not suppose to use the library's sort function for this problem.

k <= n

Example

Example1

Input:

[3,2,2,1,4]

4

Output:

[1,2,2,3,4]

Example2

Input:

[2,1,1,2,2]

2

Output:

[1,1,2,2,2]

Challenge

A rather straight forward solution is a two-pass algorithm using counting sort. That will cost O(k) extra memory. Can you do it without using extra memory?

思路:

这个题非常有趣,如果直接用快排也可以得到结果,但是时间复杂度是O(nlogn),参数k的给定就是用来将时间复杂度优化到O(nlogk)的,具体做法就是pivot用k来划分,这里另外一点与快排不一样的是,左边指针在移动的条件是小于等于,而快排的是小于,据说是因为pivot选的时候偏左?

另外题目中提到的另一种计数排序,其时间和空间复杂度均是O(n + k), k是待排序的整数的范围。注意计数排序只适用于确定数目范围的排序,是一种不基于比较的排序。

代码:

计数排序的代码

相关文章

  • 143. Sort Colors II

    Description Given an array ofnobjects withkdifferent colo...

  • 数组follow-up

    1.Sort Colors[Sort Colors]https://leetcode.com/problems/s...

  • Sort

    Sort Colors improve: Wiggle Sort Merge Intervals

  • Sort Colors

    Given an array with n objects colored red, white or blue,...

  • Sort Colors

    Given an array with n objects colored red, white or blue,...

  • Sort Colors

    计数排序解法 ​ ​ 三路快排解法 ​ 画图/变量定义 , 区间定义/伪代码 使用keynote画效果还不错​正确...

  • Sort Colors

    https://leetcode.com/problems/sort-colors/简化题意就是,有一个arr,里...

  • 75. Sort Colors | 88. Merge Sort

    75. Sort Colors 题目要求见:https://leetcode.com/problems/sort-...

  • 75 sort colors

    Given an array with n objects colored red, white or blue,...

  • sort-colors

    荷兰国旗问题

网友评论

      本文标题:143. Sort Colors II

      本文链接:https://www.haomeiwen.com/subject/vuqhqctx.html