博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Sort Colors
阅读量:7079 次
发布时间:2019-06-28

本文共 2072 字,大约阅读时间需要 6 分钟。

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.

荷兰国旗问题。

1.问题描述:

我们将乱序的红白蓝三色小球排列成有序的红白蓝三色的同颜色在一起的小球组。这个问题之所以叫荷兰国旗,是因为我们可以将红白蓝三色小球想象成条状物,有序排列后正好组成荷兰国旗。

2.问题分析:

这个问题我们可以将这个问题视为一个数组排序问题,这个数组分为前部,中部和后部三个部分,每一个元素(红白蓝分别对应0、1、2)必属于其中之一。由于红、白、蓝三色小球数量并不一定相同,所以这个三个区域不一定是等分的,也就是说如果我们将整个区域放在[0,1]的区域里,由于三色小球之间数量的比不同(此处假设1:2:2),可能前部为[0,0.2),中部为[0.2,0.6),后部为[0.6,1]。我们的思路如下:将前部和后部各排在数组的前边和后边,中部自然就排好了。具体的:

设置两个标志位begin和end分别指向这个数组的开始和末尾,然后用一个标志位current从头开始进行遍历:

1)若遍历到的位置为0,则说明它一定属于前部,于是就和begin位置进行交换,然后current向前进,begin也向前进(表示前边的已经都排好了)。

2)若遍历到的位置为1,则说明它一定属于中部,根据总思路,中部的我们都不动,然后current向前进。

3)若遍历到的位置为2,则说明它一定属于后部,于是就和end位置进行交换,由于交换完毕后current指向的可能是属于前部的,若此时current前进则会导致该位置不能被交换到前部,所以此时current不前进。而同1),end向后退1。

以上原文:http://www.cnblogs.com/sharpfeng/archive/2012/09/05/2671630.html

1 class Solution { 2 public: 3     void sortColors(int A[], int n) { 4         int begin = 0, end = n - 1, cur = 0, tmp; 5         while (cur <= end) { 6             if (A[cur] == 0) { 7                 tmp = A[cur]; 8                 A[cur++] = A[begin]; 9                 A[begin++] = tmp;10             } else if (A[cur] == 2) {11                 tmp = A[cur];12                 A[cur] = A[end];13                 A[end--] = tmp;14             } else {15                 ++cur;16             }17         }18     }19 };

因为只有0、1、2,可以直接统计0、1、2的数量,然后挨个放到数组里,同样是O(n)的复杂度,但是要遍历两遍数组。

1 class Solution { 2 public: 3     void sortColors(int A[], int n) { 4         int red = 0, white = 0, blue = 0; 5         for (int i = 0; i < n; ++i) { 6             if (A[i] == 0) ++red; 7             if (A[i] == 1) ++white; 8             if (A[i] == 2) ++blue; 9         }10         int idx = 0;11         while (red--) A[idx++] = 0;12         while (white--) A[idx++] = 1;13         while (blue--) A[idx++] = 2;14     }15 };

 

你可能感兴趣的文章
hbase shell状态下回退键不好用 (scureCRT)
查看>>
提高Python运行效率的六个窍门
查看>>
蓝懿教育第十四日记录
查看>>
python+spacy--------填坑
查看>>
堆是实现
查看>>
destoon6.0友情链接标签写法以及设置方法
查看>>
QT 全屏显示子窗口
查看>>
Android DataBase
查看>>
初来乍到,简单说一个web开发中遇到的神奇页面全选问题。
查看>>
C言语接口处置函数
查看>>
阿里云WindowsServer2016安装独立的Apache和PHP
查看>>
最简单方便的ip-mac绑定,透明网桥如何实现IP-MAC绑定?
查看>>
硬盘结构
查看>>
开源跨平台移动项目Ngui【入门】
查看>>
Ubuntu添加用户实用指南
查看>>
时空大数据来了,纽约公开11亿条出租车和Uber原始数据(英文版)
查看>>
Dharma勒索软件继续大肆传播,据称已有100多家希腊网站沦陷
查看>>
成为JavaGC专家(1)—深入浅出Java垃圾回收机制
查看>>
Linux学习笔记(十七) vim
查看>>
三十二、iptables filter表小案例、iptables nat表应用
查看>>