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?

 class Solution {
public:
void swap(int &a, int &b){
int temp = a;
a = b;
b = temp;
}
void sortColors(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (n<) return; int first = ;
int last = n-;
while(first<n && ==A[first])
first++;
while(last>= && ==A[last])
last--; int i=first;
while(first < last && i<=last){
if (==A[i]){
swap(A[i],A[last]);
last--;
while(last>= && ==A[last])
last--;
}else if(==A[i]){
swap(A[i],A[first]);
first++;
if(i<first) i=first;
while(first<n && ==A[first])
first++;
}else{
i++;
}
}
}
};

我的答案

思路:如果只需要一次遍历,就地排序,其实在循环到每个数的时候要比两次遍历多做一些事情。因为0肯定是排在前面的,2肯定是排在后面的,指定两个指针,分别指向数组的两头,然后往中间缩进,注意分别讨论遍历到0,1,2时应该做何种运算,何种操作即可。

[leetcode.com]算法题目 - Sort Colors的更多相关文章

  1. LeetCode 75. 颜色分类(Sort Colors) 30

    75. 颜色分类 75. Sort Colors 题目描述 给定一个包含红色.白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色.白色.蓝色顺序排列. 此题中, ...

  2. LeetCode(75) Sort Colors

    题目 Given an array with n objects colored red, white or blue, sort them so that objects of the same c ...

  3. [leetcode.com]算法题目 - Restore IP Addresses

    Given a string containing only digits, restore it by returning all possible valid IP address combina ...

  4. [leetcode.com]算法题目 - Jump Game

    Given an array of non-negative integers, you are initially positioned at the first index of the arra ...

  5. [leetcode.com]算法题目 - Maximum Subarray

    Find the contiguous subarray within an array (containing at least one number) which has the largest ...

  6. [leetcode.com]算法题目 - Gray Code

    The gray code is a binary numeral system where two successive values differ in only one bit. Given a ...

  7. [leetcode.com]算法题目 - Same Tree

    Given two binary trees, write a function to check if they are equal or not. Two binary trees are con ...

  8. [leetcode.com]算法题目 - Triangle

    Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent n ...

  9. [leetcode.com]算法题目 - Length of Last Word

    Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the l ...

随机推荐

  1. php与html代码的若干转换

    以前懵懵懂懂的看过,没怎么在意,现在总结一下 一般来说,像留言板之类的content,用这样的就够了: $content=addslashes(htmlspecialchars($_POST['con ...

  2. JWT-Token登陆校验

    JWT:就是靠给客户端(浏览器)一个规范凭证(签名),然后服务器解析签名,代替原有的session存值. 不带refreshToken的JWT例子:https://blog.csdn.net/u011 ...

  3. MVVM中viewmodel的理解

    网上有人写了这段话,我也有同感,特别是第一种用法,很重要,后一种用法,我觉得是把第一种用法加入controller中了. 第一种 “view model” 是 “model for the view” ...

  4. css兼容技巧

    CSS兼容常用技巧 请尽量用xhtml格式写代码,而且DOCTYPE影响 CSS 处理,作为W3C标准,一定要加DOCTYPE声明. 1.div的垂直居中问题 vertical-align:middl ...

  5. servlet中请求转发获取数据等,,,

    String uname= req.getParameter("uname");  获取请求的字符串 req.setAttribute("str"," ...

  6. mysql 批量杀进程

    select concat('KILL ',id,';') from information_schema.processlist where user='root';

  7. fastq-to-fasta转换及fasta拆分、合并

    格式转换: use awk :awk 'BEGIN{P=1}{if(P==1||P==2){gsub(/^[@]/,">");print}; if(P==4)P=0; P++ ...

  8. 假期训练七(hdu-2845 dp,hdu-1846,2188 巴什博奕)

    题目一:传送门 思路:动态规划,从每一行来看,每次更新求出这一点的最大值,dp[i]=MAX(dp[i-1],dp[i]+dp[i-2]),不会出现 两个数字相邻的情况:先对行进行更新,再对列进行更新 ...

  9. Educational Codeforces Round 51 F. The Shortest Statement(lca+最短路)

    https://codeforces.com/contest/1051/problem/F 题意 给一个带权联通无向图,n个点,m条边,q个询问,询问两点之间的最短路 其中 m-n<=20,1& ...

  10. C++STL queue

    queue队列 先进先出 queue<int> q1; q1.push();//插入元素 q1.front();//求队头元素 q1.pop();//删除队头元素 q1.empty();/ ...