[LeetCode] Sort Colors
来源:互联网 发布:上古世纪人物捏脸数据 编辑:程序博客网 时间:2024/06/15 02:16
Given an array with n objects colored red, white or blue,sort them so that objects of the same color are adjacent, with thecolors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent thecolor red, white, and blue respectively.
Note:
You are not suppose to use the library's sort function for thisproblem.
Follow up:
A rather straight forward solution is a two-pass algorithm usingcounting sort.
First, iterate the array counting number of 0's, 1's, and 2's, thenoverwrite array with total number of 0's, then 1's and followed by2's.
[Solution]
class Solution {
public:
void sortColors(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int i = 0, red = 0, blue = n-1;
// one pass
while(i <= blue){
// fill 0s
if(A[i] == 0){
swap(A[red++], A[i++]);// 从A[red]交换过来的只可能是0或1,如果是0,则必然red==i
}
// count 1s
else if(A[i] == 1){
i++;
}
// fill 2s
else if(A[i] == 2){
swap(A[i], A[blue--]);
}
}
}
};
说明:版权所有,转载请注明出处。Coder007的博客
- 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
- [LeetCode] Validate Binary Search Tree
- [LeetCode] Surrounded Regions
- httpurlconnnection_newstop
- [LeetCode] Word Search
- [LeetCode] String to Integer(atoi)
- [LeetCode] Sort Colors
- [LeetCode] Sqrt
- 图的存储(前向星)
- [LeetCode] Simplify Path
- 《高性能SQL调优精要与案例解析》一书谈SQL调优(SQL TUNING或SQL优化)学习
- [LeetCode] N-Queens
- [LeetCode] N-Queens II
- [LeetCode] Restore IP Addresses
- RecyclerView和购物车选择模式