【Leetcode】Leetcode 75.颜色分类

Leetcode 75.颜色分类

题目:

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

此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。

注意:
不能使用代码库中的排序函数来解决这道题。

示例:

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

进阶:

一个直观的解决方案是使用计数排序的两趟扫描算法。
首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。
你能想出一个仅使用常数空间的一趟扫描算法吗?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-colors

思路:

官方解答

通过代码:

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

复杂度分析

时间复杂度 :由于对长度 NN的数组进行了一次遍历,时间复杂度为O(N)O(N) 。
空间复杂度 :由于只使用了常数空间,空间复杂度为O(1)O(1) 。

发布了97 篇原创文章 · 获赞 55 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/voidfaceless/article/details/103217822