[路飞]leetcode-75.颜色分类

119 阅读1分钟

给定一个包含红色、白色和蓝色、共 n 个元素的数组 nums ,原地**对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。

我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。力扣原文

必须在不使用库的sort函数的情况下解决这个问题。 示例 1:

输入: nums = [2,0,2,1,1,0]
输出: [0,0,1,1,2,2]

示例 2:

输入: nums = [2,0,1]
输出: [0,1,2]

解题:

var sortColors = function (nums) {
  const swap = (list, i, j) => {
    [list[i], list[j]] = [list[j], list[i]];
  };
  let red = 0,index=0
    blue = nums.length - 1;
  while (index <=blue) {
    switch (nums[index]) {
      case 0:
        swap(nums, red++, index);
        index++;
        break;
      case 1:
        index++;
        break;
      case 2:
        swap(nums, blue--, index);
        break;
    }
  }
};