Leetcode|75. 颜色分类【笔记】

链接

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

前言

题目

给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
示例1:

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

示例 2:

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

示例 3:

输入:nums = [0]
输出:[0]

示例4:

输入:nums = [1]
输出:[1]

提示

  • n == nums.length
  • 1 <= n <= 300
  • nums[i] 为 0、1 或 2

进阶

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

关键

本人思路

  • 最简单办法,需进阶
  • 调用现成排序函数
class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        return nums.sort()

思路1

  • 单指针
  • 第一次遍历:把值为0的位置找出来,排到头部(靠近0的位置),这样0就放在列表的前端
  • 第二次遍历:把值为1的位置找出来,排到头部(相对靠近0的位置),这样1就放在列表的中端(0的后面),从而将2放在列表尾端
class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        ptr = 0
        n = len(nums)
        for i in range(n):
            if nums[i]==0:
                nums[ptr], nums[i] = nums[i], nums[ptr]
                ptr+=1
        for i in range(n):
            if nums[i]==1:
                nums[ptr], nums[i] = nums[i], nums[ptr]
                ptr+=1
  • 时间复杂度:O(n),其中 n 是数组nums的长度。

  • 空间复杂度:O(1)。

思路2

  • 三指针
class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        n = len(nums)
        left, point = 0, 0
        right = n-1
        while point <= right:
            if nums[point]==0:
                nums[point], nums[left] = nums[left], nums[point]
                left+=1
                point+=1
            elif nums[point]==2:
                nums[point], nums[right] = nums[right], nums[point]
                right-=1
            else:
                point+=1

疑问

参考

[1] 颜色分类
[2] 75. 颜色分类 Python指针一遍通过!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值