美文网首页
[TwoPointer]75. Sort Colors

[TwoPointer]75. Sort Colors

作者: 野生小熊猫 | 来源:发表于2019-02-10 07:15 被阅读0次
  • 分类:TwoPointer
  • 时间复杂度: O(n)
  • 空间复杂度: O(1)

75. Sort Colors

Given an array with n objects colored red, white or blue, sort them in-place 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.

Example:

Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

Follow up:

  • A rather straight forward solution is a two-pass algorithm using counting sort.
    First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
  • Could you come up with a one-pass algorithm using only constant space?

代码:

O(1)空间解法:

class Solution:
    def sortColors(self, nums: 'List[int]') -> 'None':
        """
        Do not return anything, modify nums in-place instead.
        """
        first=0
        last=len(nums)-1
        while(first<last and nums[first]==0):
            first+=1
        while(last>0 and nums[last]==2):
            last-=1
            
        i=first
        while(i<=last):
            if nums[i]==0:
                temp=nums[first]
                nums[first]=0
                nums[i]=temp
                i+=1
                first+=1
            elif nums[i]==2:
                temp=nums[last]
                nums[last]=2
                nums[i]=temp
                last-=1
            else:
                i+=1

讨论:

1.看的youtube上篮子王的讲解,很清楚,受用
2.i<=last是指走到了last才算结束
3.对前面换,换过来的肯定小,对后面换,换过来的不知道大小?

相关文章

网友评论

      本文标题:[TwoPointer]75. Sort Colors

      本文链接:https://www.haomeiwen.com/subject/qtjteqtx.html