# 题目地址

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

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

举报原因： 您举报文章：深度学习：神经网络中的前向传播和反向传播算法推导 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)