# 一天一道LeetCode

## （一）题目

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.

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?

## （二）解题

### 1、最简单的方法

class Solution {
public:
void sortColors(vector<int>& nums) {
sort(nums.begin(),nums.end());
}
};

### 2、两个指针

class Solution {
public:
void sortColors(vector<int>& nums) {
int start = 0;
int end = nums.size()-1;
for(int i = 0 ; i<nums.size();i++)//把0交换到前面
{
if(nums[i]==0) {
if(i!=start) swap(nums[i],nums[start]);
start++;
}
}
for(int i = nums.size()-1 ; i>=start ;i--)//把2交换到尾部
{
if(nums[i]==2){
if(i!=end) swap(nums[i],nums[end]);
end--;
}
}
}
};

### 3、两个指针优化版

class Solution {
public:
void sortColors(vector<int>& nums) {
int i = 0, j = i, k = nums.size() - 1;
while(j <= k){
if(nums[j] == 0) swap(nums[i++], nums[j++]);//0交换到前面
else if(nums[j] == 1) j++;//1保持不动
else swap(nums[k--], nums[j]);//2交换到尾部
}
}
};

## leetcode 75. Sort Colors 很不错的3种元素排序方法 + O（n）

Given an array with n objects colored red。 white or blue。 sort them so that objects of the same colo...

## leetcode-75 Sort Colors

• sole_cc
• 2015年03月15日 11:05
• 321

## [leetcode] 75. Sort Colors

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

## LCP075 LeetCode 75. Sort Colors

Total Accepted: 100513 Total Submissions: 287992 Difficulty: Medium Given an array with n...

## Leetcode 75：Sort Colors

Sort Colors Given an array with n objects colored red, white or blue, sort them so that objects of ...

## leetcode：75. Sort Colors

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

## Leetcode75 - Sort Colors（two pointers）

• Lzedo
• 2017年01月19日 23:17
• 87

## LeetCode 75 Sort Colors

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

## LeetCode(75)Sort Colors (荷兰三色旗问题 Dutch National Flag)

举报原因： 您举报文章：【一天一道LeetCode】#75. Sort Colors 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)