[leetcode sort]75. Sort Colors

Given an array with n objects colored red, white or blue, sort them 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.

解法1:

统计每个颜色出现的次数,这个方法比较简单易懂

 1 class Solution(object):
 2     def sortColors(self, nums):
 3         flag = [0,0,0]
 4         for i in nums:
 5             flag[i] += 1
 6         for n in range(flag[0]):
 7             nums[n] = 0
 8         for n in range(flag[1]):
 9             nums[flag[0]+n]=1
10         for n in range(flag[2]):
11             nums[flag[0]+flag[1]+n] = 2

解法2:

在评论区总是能发现一些很漂亮的方法,方法和快排比较相似

 1 class Solution(object):
 2     def sortColors(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: void Do not return anything, modify nums in-place instead.
 6         """
 7         i,start,end = 0,0,len(nums)-1
 8         while i<=end:
 9             if nums[i]==0:
10                 nums[i]=nums[start]
11                 nums[start]=0
12                 start += 1
13             elif nums[i]==2:
14                 nums[i]=nums[end]
15                 nums[end]=2
16                 end -= 1
17                 i -= 1 #交换后此位置的数未考虑,要重新考虑
18             i += 1

解法3:

最帅的是这种方法,类似于快排,指针i,j分别处理以类数据

 1 class Solution(object):
 2     def sortColors(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: void Do not return anything, modify nums in-place instead.
 6         """
 7         i,j = 0,0
 8         for k in range(len(nums)):
 9             v = nums[k]
10             nums[k] = 2
11             if v<2:
12                 nums[j]=1
13                 j += 1
14             if v == 0:
15                 nums[i]=0
16                 i += 1
原文地址:https://www.cnblogs.com/fcyworld/p/6511535.html