zoukankan      html  css  js  c++  java
  • 75. 颜色分类 leetcode

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

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

    注意:

      1. cur 遍历到0时,与left指针交换值,cur+=1, left+=1

      2. cur 遍历到1时, 不管它,直接cur+=1, 因为交换了0与2最后1会自动在中间

      3. cur 遍历到2时, 交换cur与right指针的值,right-=1,这里cur不动,因为需要再判断交换过来的cur的值

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

    解决原地问题的思路:

      1.三指针,0的有边界,2的左边界,当前遍历值,while cur <= right_boundary_of_2:

       2.代码中标记的两行,只有在与左边0呼唤之后,才会 i++ ,因为换过去的是0,就达到了把0放在左边的目的。

        其实这里我还是没想太明白,以后再想把

  • 相关阅读:
    [leetcode-135-Candy]
    [leetcode-151-Reverse Words in a String]
    [leetcode-139-Word Break]
    [leetcode-129-Sum Root to Leaf Numbers]
    [leetcode-143-Reorder List]
    [leetcode-141-Linked List Cycle]
    oracle 环境变量(中文显示乱码)
    Oracle 自增长id
    Spring.net 事件的注入
    Spirng.net 替换任意方法
  • 原文地址:https://www.cnblogs.com/ChevisZhang/p/12436447.html
Copyright © 2011-2022 走看看