作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/sort-colors/description/

题目描述

Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

Note:

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

Example:

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

Follow up:

  • A rather straight forward solution is a two-pass algorithm using counting sort.
    First, iterate the array counting number of 0’s, 1’s, and 2’s, then overwrite array with total number of 0’s, then 1’s and followed by 2’s.

  • Could you come up with an one-pass algorithm using only constant space?

题目大意

对乱序的0,1,2三个数字进行排序,保证结果是相同元素聚在一起。

解题方法

计数排序

因为只有三个数,所以简单的方法是计数排序。第一次遍历,统计出这三个数字出现的次数,第二次遍历,根据三个数字的次数对原列表进行修改。

from collections import Counter
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
count = Counter(nums)
for i in xrange(len(nums)):
if i < count[0]:
nums[i] = 0
elif i < count[0] + count[1]:
nums[i] = 1
else:
nums[i] = 2

双指针

我看到这个题的时候,很明显的看出是要把一个数组分成三段,分别是小于v,等于v和大于v。由于只有三个数字,所以也就是0,1,2分别聚在一起。所以,这个题的考点来自快排之三项切分快速排序。在《算法》第四版中有介绍,也可以看快速排序及三向切分快速排序

下面是题目讲解:

如果只能扫一遍,很容易想到的就是左边存放0和1,右边存放2.两边往中间靠。

设置两个指针,zero和two;zero指向第一个1的位置(0串的末尾),two指向第一个非2的位置。然后用i对nums进行遍历:

然后使用i从头到尾扫一遍,直到与two相遇。

i遇到0就换到左边去,遇到2就换到右边去,遇到1就跳过。

需要注意的是:由于zero记录第一个1的位置,因此A[zero]与A[i]交换后,A[zero]为0,A[i]为1,因此i++,zero++;

而two记录第一个非2的位置,可能为0或1,因此A[two]与A[i]交换后,A[two]为2,A[i]为0或1,i不能前进,要后续判断。

class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
zero = 0
two = len(nums) - 1
i = 0
while i <= two:
if nums[i] == 0:
nums[zero], nums[i] = nums[i], nums[zero]
i += 1
zero += 1
elif nums[i] == 1:
i += 1
elif nums[i] == 2:
nums[two], nums[i] = nums[i], nums[two]
two -= 1

日期

2018 年 2 月 27 日
2019 年 1 月 5 日 —— 美好的周末又开始了

【LeetCode】75. Sort Colors 解题报告(Python)的更多相关文章

  1. 【LeetCode】Sort Colors 解题报告

    [题目] Given an array with n objects colored red, white or blue, sort them so that objects of the same ...

  2. LeetCode 75. Sort Colors (颜色分类):三路快排

    Given an array with n objects colored red, white or blue, sort them in-place so that objects of the ...

  3. LeetCode: Sort Colors 解题报告

    Sort ColorsGiven an array with n objects colored red, white or blue, sort them so that objects of th ...

  4. C#版 - LeetCode 148. Sort List 解题报告(归并排序小结)

    leetcode 148. Sort List 提交网址: https://leetcode.com/problems/sort-list/  Total Accepted: 68702 Total ...

  5. leetCode 75.Sort Colors (颜色排序) 解题思路和方法

    Given an array with n objects colored red, white or blue, sort them so that objects of the same colo ...

  6. LeetCode 75. Sort Colors (python一次遍历,模拟三路快排)

    LeetCode 75. Sort Colors (python一次遍历,模拟三路快排) 题目分析: 本题需要实现数字只包含0,1,2的排序,并且要求一次遍历. 由于只用把数字隔离开,很容易想到快排的 ...

  7. [LeetCode] 75. Sort Colors 颜色排序

    Given an array with n objects colored red, white or blue, sort them in-place so that objects of the ...

  8. LeetCode 75. Sort Colors(排序颜色)

    Given an array with n objects colored red, white or blue, sort them so that objects of the same colo ...

  9. Leetcode 75. Sort Colors

    Given an array with n objects colored red, white or blue, sort them so that objects of the same colo ...

随机推荐

  1. ggplot2 颜色渐变(离散颜色)设置

    一.示例数据准备 数据格式如下: 二.作图 1.直接作图结果如下,默认蓝色渐变. 1 ggplot(df,aes(x=BP_A,y=P.value,colour=R2))+ 2 geom_point( ...

  2. Oracle-常用表的查询、增加列、删除列、修改列值功能【增删改查】

    #查看表 select * from `竟企区域数据分析` #在表第一列新增名为"年月"的列alter table `竟企区域数据分析` add column 年月 varchar ...

  3. Python序列化,json&pickle&shelve模块

    1. 序列化说明 序列化可将非字符串的数据类型的数据进行存档,如字典.列表甚至是函数等等 反序列化,将通过序列化保存的文件内容反序列化即可得到数据原本的样子,可直接使用 2. Python中常用的序列 ...

  4. QQ空间技术架构之深刻揭秘

    QQ空间技术架构之深刻揭秘 来源: 腾讯大讲堂  发布时间: 2012-05-17 17:24  阅读: 7822 次  推荐: 4   [收藏]   QQ 空间作为腾讯海量互联网服务产品,经过近七年 ...

  5. 从零构建Java项目(Maven+SpringBoot+Git) #02 奥斯丁项目

    前两天我说要写个项目来持续迭代,有好多小伙伴都表示支持和鼓励,项目的第一篇这不就来了么~我给项目取了个名字,英文名叫做:austin,中文名叫做:奥斯丁 名字倒没有什么特别的含义,我单纯觉得这个名字好 ...

  6. pow()是如何实现的?

    如1.5 ** 2.5,如何计算?似乎是这样的: 1. cmath calculates pow(a,b) by performing exp(b * log(a)). stackoverflow 2 ...

  7. python web工程师跳巢攻略

    python web工程师跳巢攻略 流程 一面问基础 二面问项目 三面问设计(经验) web请求的流程 浏览器 负载均衡 web框架 业务逻辑 数据库缓存 后端技术栈 python语言基础 语言特点 ...

  8. Https原理及证书管理

    Https原理及证书管理 SSL(Secure Sockets Layer,安全套接层)/TLS(Transport Layer Security,传输层安全)保证了客户端web服务器的连接安全.客户 ...

  9. shell条件测试语句实例-测试apache是否开启

    终于理解了shell条件测试语句"!="和"-n"的用法区别,于是有了如下的shell脚本,做为练习. 第一种方法:测试apache是否开启?字符串测试 #!/ ...

  10. ES在项目中的测试

    1.application.yml server: port: ${port:40100}spring: application: name: xc-search-servicexuecheng: e ...