Sort Colors

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.

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?


Solution:

扫描两趟算法:

  即 counting sort,第一趟给 0、1、2 分别计数,第二趟直接在相应位置上 overwrite value。

扫描一趟算法:

  由于整个array只有三个值,我们实际上需要做的工作便是把所有的 0 移到 array 头部位置,把所有的 2 移到 array 尾部位置,剩下的 1 便自然被挪到了中间位置。

  考虑两个指针,一个head指示“0头部”即将要“占领”到的位置,初始值为0,递增;另一个tail指示“2尾部”即将要“占领”到的位置,初始值为 len(nums)-1,递减。

  从左至右扫描,当扫描到当前位置 i 时,如果值为 0 并且不在“0头部”( i >= head )时,此时需要把 i 与 head 进行值交换,“0头部”长度自然拓展1,而 i 位置上的值变得不确定,此时保持 i 的值不变;如果值为 1 并且不在“2尾部”( i <= tail )时,此时需要把 i 与 tail 进行值交换,“2尾部”长度自然拓展1,而 i 位置上的值变得不确定,此时保持 i 的值不变;其他情况(在“0头部”或“2尾部”,或者当前位置值为1)则直接把扫描指针 i 加 1 即可。

  最后,本来扫描可以一直进行到 len(nums)-1,而由于扫描时已经可以确定“2尾部”中的2全部都已经在合适的位置上,所以扫描到 tail 即可终止循环( i <= tail )。

  代码如下:

  

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

【LeetCode】Sort Colors的更多相关文章

  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】Sort Colors 数组排序

    题目:Sort color <span style="font-size:18px;">/*LeetCode sort colors 题目:输入一个数组.包括0,1,2 ...

  3. 【leetcode】Sort Colors(middle)☆

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

  4. 【Leetcode】Sort List JAVA实现

    Sort a linked list in O(n log n) time using constant space complexity. 1.分析 该题主要考查了链接上的合并排序算法. 2.正确代 ...

  5. 【LeetCode】 sort list 单清单归并

    称号:Sort a linked list in O(n log n) time using constant space complexity. 思路:要求时间复杂度O(nlogn) 知识点:归并排 ...

  6. 【数组】Sort Colors

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

  7. 【leetcode】Sort List (middle)

    Sort a linked list in O(n log n) time using constant space complexity. 思路: 用归并排序.设输入链表为S,则先将其拆分为前半部分 ...

  8. 【leetcode】Sort List

    Sort List Sort a linked list in O(n log n) time using constant space complexity.   需要采用归并排序对链表进行操作. ...

  9. 【Leetcode】Sort List (Sorting)

    这个问题需要与归并排序排两个名单,基本思路分为切割与合并 合并后的代码Merge Two Sorted List里已经讲得非常清楚了. 所以这里直接给出代码. public ListNode merg ...

随机推荐

  1. js数组操作大全(转载)

    转载原网址:http://hi.baidu.com/jspboy/item/4923fffb52a28014fe35823a shift:删除原数组第一项,并返回删除元素的值:如果数组为空则返回und ...

  2. HTTP 错误 500.21 - Internal Server Error

    HTTP 错误 500.21 - Internal Server Error 处理程序“PageHandlerFactory-Integrated”在其模块列表中有一个错误模块“ManagedPipe ...

  3. Python:list用法

    list是一种有序的集合,可以随时添加和删除其中的元素. 定义 空list >>> a_list=[] >>> a_list [] 普通 >>> ...

  4. android .9图的作用

    参考:http://www.cnblogs.com/lianghui66/archive/2013/01/08/2850581.html .9图的介绍 1.这种格式的图片是Android平台上一种被拉 ...

  5. 手机客户端UI测试常见的测试点

    1.各种分辨率下,显示正常.现市场上主流的塞班V3系统手机为240*320.320*240.WM系统主要为240*320.320*480.Android系统主要为320*480,Iphone系统为32 ...

  6. [字符哈希] POJ 3094 Quicksum

    Quicksum Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 16488   Accepted: 11453 Descri ...

  7. AJAX格式

    var xmlHttp;function getXmlHttp(){ if(window.ActiveXObject){ xmlHttp = new ActiveXObject("MICRO ...

  8. Jmeter性能测试入门(转)

    出处:http://www.cnblogs.com/by-dream/p/5611555.html Jmeter性能测试步骤 1. 添加线程组之后,先设置这两项: 2. 添加一个http请求 被测的u ...

  9. Bootstrap<基础九>辅助类

    Bootstrap 中的一些可能会派上用场的辅助类. 文本 以下不同的类展示了不同的文本颜色.如果文本是个链接鼠标移动到文本上会变暗: 类 描述   .text-muted "text-mu ...

  10. [vijos P1040] 高精度乘法

    如果这次noip没考好,完全是因为从7月29日之后就没有再写过程序了.说起来,真是一个泪流满面的事实… 那这样一个弱智题练手恢复代码能力,竟然还花了我两个晚上(当然不是两整个晚上…) 第一天TLE了, ...