75. Sort Colors

Problem:

Given an array with n objects colored red, white or blue, sort them in-placeso 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.

Example:

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

Follow up:

Solution:

One-pass algorithm.

Take the idea of the partition algorithm from quick sort. Use 1 as pivot.

Count the number of sorted 0s and 2s so that we know where to swap.

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var sortColors = function(nums) {
  const len = nums.length
  let zeroEnd = 0
  let twoStart = len - 1
  let i = 0
  while (i <= twoStart) {
    if (nums[i] === 0 && i !== zeroEnd) {
      const t = nums[i]
      nums[i] = nums[zeroEnd]
      nums[zeroEnd] = t
      zeroEnd++
    } else if (nums[i] === 2 && i !== twoStart) {
      const t = nums[i]
      nums[i] = nums[twoStart]
      nums[twoStart] = t
      twoStart--
    } else {
      i++
    }
  }
};

Template generated via Leetmark.