#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
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.
'''
class Solution(object):
def sortColors(self, nums):
"""未考虑输入不合法
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
num0 = num1 = 0 #分别0,1的个数
for i in nums:
if i == 0:
num0 += 1
elif i == 1:
num1 += 1
for i in range(num0):
nums[i] = 0
for i in range(num0,num0 + num1):
nums[i] = 1
for i in range(num0 + num1,len(nums)):
nums[i] = 2
if __name__ == "__main__":
s = Solution()
a = [0,1,2,1,2,0,1,1,1,2]
s.sortColors(a)
print a
74 leetcode - Sort Colors
最新推荐文章于 2025-08-08 00:00:33 发布