LeetCode-Sort Colors
2013-09-20 16:17
295 查看
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?
例如10022
20021->10022->20012->10022->00122
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?
例如10022
20021->10022->20012->10022->00122
class Solution { public: void sortColors(int A[], int n) { int p0=0,p1=n-1,p2=n-1; while(p0<=p1){ if(A[p0]==2){ int t=A[p2]; A[p2]=A[p0]; A[p0]=t; p2--; if(p2<p1)p1=p2; } else if(A[p0]==1){ int t=A[p1]; A[p1]=A[p0]; A[p0]=t; p1--; } else{ p0++; } } } };
相关文章推荐
- 128_leetcode_Sort Colors
- LeetCode-M-Sort Colors
- Sort Colors leetcode java
- Leetcode 75 Sort Colors
- Sort Colors - Leetcode
- leetcode Sort Colors
- [LeetCode] Sort Colors
- LeetCode 75. Sort Colors(排序颜色)
- leetcode_75. Sort Colors题解
- [LeetCode] 75. Sort Colors java
- LeetCode 075 Sort Colors
- LeetCode: Sort Colors
- [Leetcode]Sort Colors
- [LeetCode]题解(python):075-Sort Colors
- [LeetCode] Sort Colors
- leetcode题解-75. Sort Colors && 442. Find All Duplicates in an Array
- [leetcode] Sort Colors
- LeetCode-Sort Colors
- LeetCode - Refresh - Sort Colors
- LeetCode - Sort Colors