跳转至

75.sort-colors

Statement

Metadata
  • Link: 颜色分类
  • Difficulty: Medium
  • Tag: 数组 双指针 排序

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

我们使用整数 0、 12 分别表示红色、白色和蓝色。

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

 

示例 1:

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

示例 2:

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

 

提示:

  • n == nums.length
  • 1 <= n <= 300
  • nums[i]012

 

进阶:

  • 你可以不使用代码库中的排序函数来解决这道题吗?
  • 你能想出一个仅使用常数空间的一趟扫描算法吗?

Metadata
  • Link: Sort Colors
  • Difficulty: Medium
  • Tag: Array Two Pointers Sorting

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.

 

Example 1:

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

Example 2:

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

 

Constraints:

  • n == nums.length
  • 1 <= n <= 300
  • nums[i] is either 0, 1, or 2.

 

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

Solution

from typing import List


class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        n = len(nums)
        l, r = 0, n - 1
        for i in range(n):
            pre = nums[i]
            while True:
                if nums[i] == 0:
                    while l < i and nums[l] == 0:
                        l += 1
                    nums[l], nums[i] = nums[i], nums[l]
                elif nums[i] == 2:
                    while r > i and nums[r] == 2:
                        r -= 1
                    nums[r], nums[i] = nums[i], nums[r]
                else:
                    break

                if nums[i] == pre:
                    break

                pre = nums[i]

最后更新: October 11, 2023
回到页面顶部