75. Sort Colors

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.

Follow-Up:

Could you come up with an one-pass algorithm using only constant space?

Solution: 3-Way Partition

Python:

class Solution(object):
    def sortColors(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """

        def partition(low, high, pivot):
            idx = low
            while idx <= high:
                num = nums[idx]
                if num < pivot:
                    swap(idx, low)
                    low += 1
                    idx += 1
                elif num > pivot:
                    swap(idx, high)
                    high -= 1
                else:
                    idx += 1
            return low - 1, high + 1

        def swap(i, j):
            nums[i], nums[j] = nums[j], nums[i]

        partition(0, len(nums) - 1, 1)

Java:

public class Solution {
    public void sortColors(int[] nums) {
        partition(nums, 0, nums.length - 1, 1);
    }

    private void partition(int[] nums, int low, int high, int pivot) {
        int i = low;
        while (i <= high) {
            if (nums[i] == pivot) {
                i++;
            } else if (nums[i] < pivot) {
                swap(nums, i++, low++);
            } else {
                swap(nums, i, high--);
            }
        }
    }

    private void swap(int[] nums, int left, int right) {
        int temp = nums[left];
        nums[left] = nums[right];
        nums[right] = temp;
    }
}

results matching ""

    No results matching ""