75. Sort Colors

第一种做法,但是这个很明显不是他们想要的:

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

网上看到的方法, left指针左侧都是0,right指针右侧都是2,left到i之间是1,不断移动i ,直到i与right相遇:

class Solution(object):
    def sortColors(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        left = 0
        i = 0
        right = len(nums) - 1
        while i <= right:
            if nums[i] == 0:
                temp = nums[left]
                nums[left] = nums[i]
                nums[i] = temp
                i += 1
                left += 1
            elif nums[i] == 1:
                i += 1
            else:
                temp = nums[right]
                nums[right] = nums[i]
                nums[i] = temp
                right -= 1

网上的平移的做法

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

你可能感兴趣的:(75. Sort Colors)