LeetCode OJ 系列之75 Sort Colors --Python

来源:互联网 发布:左耳最后说了什么 知乎 编辑:程序博客网 时间:2024/06/07 11:08

Problem:

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.

Answer:

class Solution(object):    def sortColors(self, nums):        """        :type nums: List[int]        :rtype: void Do not return anything, modify nums in-place instead.        """        num0 = 0        num1 = 0        num2 = 0                for i in nums:            if i == 0 : num0+=1            if i == 1 : num1+=1            if i == 2 : num2+=1        for i in range(len(nums)):            if i< num0: nums[i]=0            if i< num1+num0 and i>= num0: nums[i]=1            if i< num2+num1+num0 and i>= num1+num0: nums[i]=2

0 0