leetcode color sort
来源:互联网 发布:韩路淘宝店叫什么 编辑:程序博客网 时间:2024/06/11 02:15
问题描述:
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.
问题分析:
数组排序的平均时间复杂度是O(nlgn),该题需要在O(n)时间复杂度内完成。
因为数据的特点:输入序列中的元素只有三种类型,所以能够在线性时间内
完成。两个指针red, blue可以将数组划分成为三段。
初始值:
red = -1, blue = n, i = red + 1;(-infinite, red] RED元素[blue, +infinite) BLUE元素i in (red, blue), (red, i) GREEN元素, 该条可以认为是下面迭代过程的循环不变式
迭代过程:
while (i < blue){if (a[i] == BLUE && --blue != i){ swap(a[i], a[blue]); continue; }if (a[i] == RED && ++red != i){ swap(a[i], a[red]); }i++;}
0 0
- [leetcode] Sort Color
- leetcode color sort
- [leetcode题后感]sort color
- [Leetcode]sort Color
- <LeetCode OJ> 75. Sort Color
- LeetCode刷题(41)--Sort Color
- Sort Color
- sort color
- Sort Color
- Sort Color
- 【leetcode】Array——Sort Color(75)
- Partition Array/ Sort Color
- LeetCode75(Sort Color)
- sort k color
- LeetCode--Sort
- [leetcode][list][sort] Sort List
- LeetCode Sort Problem || Sort Colors
- LeetCode: Sort Colors
- C语言读取BMP图像到数组,BMP图片格式
- MFC一个非常明显的创建字体的方法
- 在Visual Studio 2012中编译使用HttpClient时
- Linux远程管理器xshell和xftp使用教程
- 第十四周上机项目2--(1) 带姓名的成绩单 按成绩排序
- leetcode color sort
- hdu 3313 Key Vertex BFS应用
- NOIP2014DAY2T2
- 使用JDBC连接数据库需要哪四步
- C程序
- Unity3D_常量、异常
- Ruby 2.1: objspace.so
- 如何再浮躁中更专心工作
- 内联函数和宏定义的区别