前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode: 75. Sort Colors

leetcode: 75. Sort Colors

作者头像
JNingWei
发布2018-09-27 17:00:08
4210
发布2018-09-27 17:00:08
举报
文章被收录于专栏:JNing的专栏JNing的专栏

Problem

# 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.
#
# click to show follow up.
#
# 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?

Idea

1.由于x[:red+1]都是被white指针滑过的区域,保证了x[red]一定为0,
所以当 x[white]==0 时,white和red同步加1;

2.而x[blue:]尚未被white指针滑过,所以无法保证了x[blue]一定为2,
因此当 x[white]==2 时,只有white加1;

3.注意循环条件是 white <= blue 。

AC

class Solution():
    def sortColors(self, x):
        red, white, blue = 0, 0, len(x)-1
        while white <= blue:
            if x[white] == 0:
                x[red], x[white], white, red = x[white], x[red], white+1, red+1
            elif x[white] == 1:
                white += 1
            else:
                x[white], x[blue], blue = x[blue], x[white], blue-1


if __name__ == "__main__":
    x = [2, 1, 1, 0, 0, 2]
    Solution().sortColors(x)
    assert x == [0, 0, 1, 1, 2, 2]
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年11月20日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Problem
  • Idea
  • AC
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档