[TwoPointer]75. Sort Colors
2019-02-10 本文已影响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.对前面换,换过来的肯定小,对后面换,换过来的不知道大小?