# 题目地址

https://leetcode.com/problems/sort-colors/

# 代码

## 解一

class Solution {
public:
void sortColors(vector<int>& nums) {
if (nums.size() == 0) {
return;
}
int red = 0;
int white = 0;

for (int i = 0; i != nums.size(); ++i) {
if (nums[i] == 0) {
++red;
}
if (nums[i] == 1) {
++white;
}
}

for (int i = 0; i != nums.size(); ++i) {
if (red != 0) {
nums[i] = 0;
--red;
} else if (white != 0) {
nums[i] = 1;
--white;
} else {
nums[i] = 2;
}
}
return;
}
};

## 解二

class Solution {
public:
void sortColors(vector<int>& nums) {
if (nums.empty()) {
return;
}
int size = nums.size();
int start = 0;
while (start < size && nums[start] == 0) {
start++;
}

int end = size - 1;
while (end >= 0 && nums[end] == 2) {
end--;
}

int i = start;
while (start < end && i <= end && start < size && end >= 0) {
if (nums[i] == 1) {
++i;
continue;
}
if (nums[i] == 0) {
nums[i] = nums[start];
nums[start] = 0;
start++;
} else if (nums[i] == 2){
nums[i] = nums[end];
nums[end] = 2;
end--;
if (nums[start] == 0) {
start++;
i++;
}
}
}
}
};

#### LeetCode（75） Sort Colors

2015-09-17 20:00:39

#### leetCode 75.Sort Colors (颜色排序) 解题思路和方法

2015-07-19 16:38:00

#### 【LeetCode】Sort Colors 解题报告

2014-10-13 20:51:44

#### LeetCode 75. Sort Colors（三颜色排序→K颜色排序）

2018-03-26 16:29:28

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

2014-02-10 03:42:16

#### Leetcode_75_Sort Colors

2015-01-30 07:32:32

#### Leetcode75 Sort Colors

2015-10-18 20:42:20

#### LeetCode-75. Sort Colors (JAVA)三色排序

2017-04-22 18:28:09

#### LeetCode75——Sort Colors

2015-11-17 20:23:16

#### LeetCode--Sort Colors（颜色排序）Python

2017-12-05 13:47:04