Sort Colors Problem


Description

LeetCode Problem 75.

Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.

We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.

You must solve this problem without using the library’s sort function.

Example 1:

1
2
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

Example 2:

1
2
Input: nums = [2,0,1]
Output: [0,1,2]

Example 3:

1
2
Input: nums = [0]
Output: [0]

Example 4:

1
2
Input: nums = [1]
Output: [1]

Constraints:

  • n == nums.length
  • 1 <= n <= 300
  • nums[i] is 0, 1, or 2.


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
    void sortColors(vector<int>& nums) {
        int p0 = 0, p2 = nums.size()-1;
        int curr = 0, tmp;
        while (curr <= p2) {
            if (nums[curr] == 0) {
                tmp = nums[curr];
                nums[curr] = nums[p0];
                nums[p0] = tmp;
                curr ++;
                p0 ++;
            } else if (nums[curr] == 2) {
                tmp = nums[curr];
                nums[curr] = nums[p2];
                nums[p2] = tmp;
                p2 --;
            } else {
                curr ++;
            }
        }
        return;
    }
};




Related Posts

Squares Of A Sorted Array Problem

LeetCode 977. Given an integer array nums sorted in non-decreasing...

Sort Array By Parity Problem

LeetCode 905. Given an integer array nums, move all the...

Sort Array By Parity II Problem

LeetCode 922. Given an array of integers nums, half of...

Shortest Distance To A Character Problem

LeetCode 821. Given a string s and a character c...

Reverse Only Letters Problem

LeetCode 917. Given a string s, reverse the string according...

Push Dominoes Problem

LeetCode 838. There are n dominoes in a line, and...