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

本文共 1871 字,大约阅读时间需要 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:

统计每个颜色出现的次数,这个方法比较简单易懂

1 class Solution(object): 2     def sortColors(self, nums): 3         flag = [0,0,0] 4         for i in nums: 5             flag[i] += 1 6         for n in range(flag[0]): 7             nums[n] = 0 8         for n in range(flag[1]): 9             nums[flag[0]+n]=110         for n in range(flag[2]):11             nums[flag[0]+flag[1]+n] = 2

解法2:

在评论区总是能发现一些很漂亮的方法,方法和快排比较相似

1 class Solution(object): 2     def sortColors(self, nums): 3         """ 4         :type nums: List[int] 5         :rtype: void Do not return anything, modify nums in-place instead. 6         """ 7         i,start,end = 0,0,len(nums)-1 8         while i<=end: 9             if nums[i]==0:10                 nums[i]=nums[start]11                 nums[start]=012                 start += 113             elif nums[i]==2:14                 nums[i]=nums[end]15                 nums[end]=216                 end -= 117                 i -= 1 #交换后此位置的数未考虑,要重新考虑18             i += 1

解法3:

最帅的是这种方法,类似于快排,指针i,j分别处理以类数据

1 class Solution(object): 2     def sortColors(self, nums): 3         """ 4         :type nums: List[int] 5         :rtype: void Do not return anything, modify nums in-place instead. 6         """ 7         i,j = 0,0 8         for k in range(len(nums)): 9             v = nums[k]10             nums[k] = 211             if v<2:12                 nums[j]=113                 j += 114             if v == 0:15                 nums[i]=016                 i += 1

 

转载于:https://www.cnblogs.com/fcyworld/p/6511535.html

你可能感兴趣的文章
Python和Singleton (单件)模式[转载]
查看>>
hibernate多对多单向(双向)关系映射
查看>>
二分查找题
查看>>
httpclient设置proxy与proxyselector
查看>>
python 文件单行循环读取的坑(一个程序中,文件默认只能按行循环读取一次,即使写到另一个循环里,它也只读取一次)...
查看>>
IT常用单词
查看>>
拓扑排序
查看>>
NYOJ--32--SEARCH--组合数
查看>>
day07
查看>>
【Android开发:自定义控件系列二】关于PopupWindow的注意点
查看>>
HTML——使用表格进行页面布局
查看>>
字符串统计 连续的某个字符的数量 1.1.4
查看>>
JMS
查看>>
gulpfile 压缩模板
查看>>
JAVA知多少
查看>>
Kruskal算法(转)
查看>>
CSS3 Media Queries实现响应式布局
查看>>
【34.14%】【BZOJ 3110】 [Zjoi2013]K大数查询
查看>>
【 henuacm2016级暑期训练-动态规划专题 A 】Cards
查看>>
第五篇:白话tornado源码之褪去模板的外衣
查看>>