[leetcode] Sort Colors
来源:互联网 发布:网络英语哪家好 编辑:程序博客网 时间:2024/05/21 10:21
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.
题目给出的要求是one-pass algorithm.
public class Solution { public void sortColors(int[] A) { int i = -1, j = -1; for (int p = 0; p < A.length ; p++) { int v = A[p]; A[p] = 2; if(v == 0){ A[++i] = 1; A[++j] = 0; } else if(v == 1){ A[++i] = 1; } } } }
i, j, p are used as counter in the code.
i: the number of 0, and write zero to them.
j: the number of 0 & 1, and write one to them.
p: the number of 0 & 1 & 2, and write two to them. Besides, it's also the iterator pointer.
every time, the number will be over ride to 2 at first, if it's a zero, will be over ride to 1 then, but the final result is still 0 at last.
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
- Bundle install error
- 算法研究之快速排序
- Winform 动态添加RadioButton、CheckBox 且任意分组
- Hadoop 之 注解
- 算法研究之左旋字符串
- [leetcode] Sort Colors
- White Rectangles(hdu 1510)
- poj1634
- 表达式生成满足条件的随机数据
- OC语言-----NSArray , NSMutableArray, NSNumber 基本用法
- 编程思想
- mysql的安装、C++访问mysql数据库、编码设置问题
- 网络编程时的字节顺序变换,地址变换
- [国学常识] 七情六欲八苦