0075 - Sort Colors

0075 - Sort Colors

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.

Constraints

  • n == nums.length

  • 1 <= n <= 300

  • nums[i] is 0, 1, or 2.

Follow up: Could you come up with a one-pass algorithm using only constant extra space?

Java Solution

class Solution {
    public void sortColors(int[] nums) {

        int p1 = 0;
        int p2 = nums.length - 1;
        int current = 0;
        int temp;
        
        while(current <= p2) {
            if(nums[current] == 0) {
                temp = nums[p1];
                nums[p1] = nums[current];
                nums[current] = temp;
                p1++;
                current++;
            } else if (nums[current] == 2) {
                temp = nums[p2];
                nums[p2] = nums[current];
                nums[current] = temp;
                p2--;
            } else current++;
        }
    }
}

Last updated