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])

 

参考:

思路:i记录0的个数,j记录0和1的个数,for循环是,都先把当前位置赋值为2,当前值其实小于2,就根据i、j把该值放到合适的位置

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 

 

相关文章:

  • 2022-01-20
  • 2021-06-30
  • 2021-10-23
  • 2021-10-30
  • 2022-12-23
  • 2022-03-07
  • 2021-08-11
  • 2021-06-25
猜你喜欢
  • 2021-10-29
  • 2021-07-11
  • 2021-07-22
  • 2021-06-27
  • 2022-01-27
  • 2021-05-20
  • 2022-01-13
相关资源
相似解决方案