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的个数,再分配到各个位置
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。
思路二:双哨兵一次遍历
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] 为例:
- i = 0, j = 0
- k = 0时,nums[0] = 2,下一步;
- k = 1时,nums[1] = 0,则令nums[0] = 1,j=1;num[0] = 0,i=1;
- k = 2时,nums[2] = 2,下一步;
- k = 3时,nums[3] = 1,则令nums[1] = 1,j=2;
- k = 4时,nums[4] = 1,则令nums[2] = 1,j=3;
- 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.