mycode 97.95%
class Solution(object): def sortColors(self, nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ from collections import Counter res = Counter(nums) nums[:res[0]] = [0]*res[0] nums[res[0]:res[0]+res[1]] = [1]*res[1] nums[res[0]+res[1]:] = [2]*(res[2])
reference:
Thinking: i record the number 0, j records the number 0 and 1, for loop that are first assigned to the current position 2, in fact, the current value is less than 2, according to i, j to the value in the right place
class Solution(object): def sortColors(self, nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ i = j = 0 for k in range(len(nums)): temp = nums[k] nums[k] = 2 if temp < 2: nums[j] = 1 j += 1 if temp == 0: nums[i] = 0 i += 1