LeetCode:75. Sort Colors

LeetCode:75. Sort Colors

Given an array 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.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

Note: You are not suppose to use the library's sort function for this problem.

Example:

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

将包含(0,1,2)三个数字的数组排序。

思路一:统计0,1,2的个数,再分配到各个位置

Python 代码实现

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

想法比较简单,直接统计0,1,2的个数,再分配给原数组nums。

思路二:双哨兵一次遍历

Python 代码实现

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        i = j = 0
        l = len(nums)
        for k in range(l):
            v = nums[k]
            nums[k] = 2
            if v < 2:
                nums[j] = 1
                j += 1
            if v < 1:
                nums[i] = 0
                i += 1

首先设置两个哨兵 i 和 j,初始位置都为0。然后遍历数组,每遍历到一个位置,都令该位置的元素值为2,同时判断原始值 v:

  • 如果 v < 2,则令 j 位置元素为1,同时 j 后移一位;
  • 如果 v < 1,则令 j 位置元素为1,同时 j 后移一位;再令 i 位置元素为0,同时 i 后移一位。

以 [2,0,2,1,1,0] 为例:

  1. i = 0, j = 0
  2. k = 0时,nums[0] = 2,下一步;
  3. k = 1时,nums[1] = 0,则令nums[0] = 1,j=1;num[0] = 0,i=1;
  4. k = 2时,nums[2] = 2,下一步;
  5. k = 3时,nums[3] = 1,则令nums[1] = 1,j=2;
  6. k = 4时,nums[4] = 1,则令nums[2] = 1,j=3;
  7. k = 5时,nums[5] = 0,则令nums[3] = 1,j=4;nums[1] = 0, i=2。

最终nums为[0,0,1,1,2,2]。

实际上两个哨兵的作用就是用来暂存0和1位置的指针。里面还有个重要的原则就是大的数覆盖小的数。所以每次遍历到新位置,直接用2覆盖当前位置;如果原始值为1,则覆盖前面的 j 的位置;如果为0,则先用1覆盖j位置,再用0覆盖 i 的位置。


THE END.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值