Skip to content

75. Sort Colors

https://leetcode.com/problems/sort-colors/

js
/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var sortColors = function(nums) {
  var red = 0
  var blue = nums.length - 1
  var i = 0

  while (i <= blue) {
    if (nums[i] === 0) {
      swap(nums, i, red)
      red++
      i++
    } else if (nums[i] === 2) {
      swap(nums, i, blue)
      blue--
    } else {
      i++
    }
  }

  function swap(nums, i, j) {
    var temp = nums[i]
    nums[i] = nums[j]
    nums[j] = temp
  }
}
py
class Solution(object):

    def sortColors(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        red, blue, i = 0, len(nums) - 1, 0
        while i <= blue:
            if nums[i] == 0:
                nums[i], nums[red] = nums[red], nums[i]
                red += 1
                i += 1
            elif nums[i] == 2:
                nums[i], nums[blue] = nums[blue], nums[i]
                blue -= 1
            else:
                i += 1