LeetCode--Sort Colors(颜色排序)Python

来源:互联网 发布:网络推广具体做什么 编辑:程序博客网 时间:2024/05/20 00:12

题目:

给定一个长度为n的数组,数组中包含三种颜色的球。将相同颜色的球连接排列。返回重新排列后的数组。其中0、1、2分别代表一个颜色

解题思路:

统计数组中0、1、2分别出现的次数。根据次数重新对数组进行赋值。

代码(Python):

class Solution(object):    def sortColors(self, nums):        """        :type nums: List[int]        :rtype: void Do not return anything, modify nums in-place instead.        """        count0 = 0        count1 = 0        count2 = 0        for i in nums:            if i==0:                count0+=1            elif i==1:                count1+=1            else:                count2+=1                output = []        for i in range(count0):            nums[i] = 0        for i in range(count1):            nums[i+count0] = 1        for i in range(count2):            nums[i+count0+count1] = 2

原创粉丝点击