[LeetCode]Sort Colors
来源:互联网 发布:读出图片的像素数据 编辑:程序博客网 时间:2024/06/03 16:39
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?
public class Solution { public void sortColors(int[] A) { int []B = new int[A.length]; int left = 0; int right = B.length-1; for(int i = 0;i<A.length;i++){ if(A[i]==0){ B[left] = 0; left++; }else if(A[i]==2){ B[right] = 2; right--; } } Arrays.fill(B, left, ++right, 1); for(int i=0;i<A.length;i++){ A[i] = B[i]; } }}
0 0
- LeetCode: Sort Colors
- LeetCode Sort Colors
- LeetCode : Sort Colors
- leetcode 77: Sort Colors
- Leetcode 75 Sort Colors
- leetcode 101: Sort Colors
- [LeetCode]Sort Colors
- [leetcode]Sort Colors
- LeetCode-Sort Colors
- [leetcode] Sort Colors
- [LeetCode] Sort Colors
- [leetCode] Sort Colors
- LeetCode - Sort Colors
- leetcode:Sort Colors
- LeetCode | Sort Colors
- 【LeetCode】Sort Colors
- Leetcode: Sort Colors
- [LeetCode] Sort Colors
- //2.11练习.练习4(2).p37
- 转载:时空上下文视觉跟踪(STC)算法
- 从pthread到Win32thread
- 删除cad中所有图案填充方法
- 鼠标事件
- [LeetCode]Sort Colors
- ArcGIS教程:计算分区河流(管线)总长度
- xcode6 新建的项目没有PrefixHeader.pch
- Mac系统下打包成zip发给windows查看文件乱码
- linux内核网络协议栈学习笔记:关于GRO/GSO/LRO/TSO等patch的分析和测试
- 剖析非标准波特率的设置和使用于Linux操作系统中
- 怎样设计一个好的社交网站
- C#文件及文件夹的操作
- 同步并发操作之等待一次性事件