作者: 负雪明烛
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. Mysql-单个left join 计算逻辑(一对多问题)

    BUG背景: 我们有一个订单表 和 一个 物流表 它们通过 订单ID 进行一对一的关系绑定.但是由于物流表在保存订单信息的时候没有做判断该订单是否已经有物流信息,这就变成同一个订单id在物流表中存在多 ...

  2. 8.Maximum Depth of Binary Tree

    /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode ...

  3. UE4之Slate:App默认窗口的创建流程

    UE4版本:4.24.3源码编译 Windows10 + VS2019开发环境 在先前分享的基础上,现在来梳理下App启动时默认窗口的创建流程,以及相关的类.对象之间的抽象层级: 纯C++工程配置 S ...

  4. 二进制免编译My SQL

    一 下载 MySQL 安装包教程 https://blog.csdn.net/zhan107876/article/details/100701135 ll -h mysql-5.6.47-linux ...

  5. java输入代码

    import java.util.Scanner; public class Demo59 {    public static void main(String[] args) {        / ...

  6. day8 基本数据类型之字典

    day8 基本数据类型之字典 一.字典(dict) 1.用途: 2.定义方式:在{}内用逗号分隔开多个元素,每个元素都是key:value的形式,其中value可以使任意类型,而key必须是不可变类型 ...

  7. 零基础学习java------21---------动态代理,java8新特性(lambda, stream,DateApi)

    1. 动态代理 在一个方法前后加内容,最简单直观的方法就是直接在代码上加内容(如数据库中的事务),但这样写不够灵活,并且代码可维护性差,所以就需要引入动态代理 1.1 静态代理实现 在讲动态代理之前, ...

  8. GPU随机采样速度比较

    技术背景 随机采样问题,不仅仅只是一个统计学/离散数学上的概念,其实在工业领域也都有非常重要的应用价值/潜在应用价值,具体应用场景我们这里就不做赘述.本文重点在于在不同平台上的采样速率,至于另外一个重 ...

  9. 数据源(Data Source

    数据源(Data Source)顾名思义,数据的来源,是提供某种所需要数据的器件或原始媒体.在数据源中存储了所有建立数据库连接的信息.就像通过指定文件名称可以在文件系统中找到文件一样,通过提供正确的数 ...

  10. Spring Boot下使用JSP页面

    一.创建webapp目录 在src/main下创建webapp目录,用于存放jsp文件.这就是一个普通的目录,无需执行Mark Directory As 二.创建jsp 1.指定web资源目录 在sp ...