75. Sort Colors
Given an array with n objects colored red, white or blue, sort them 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.
题解
该题思路:
1. 一个指针pl指向头(第一个不一定为0的数字),一个指针pr指向尾(右起第一个不一定为2的数字)。
2. 如果nums[i] == 0,就和左边指针指向的数字交换,如果nums[i] == 2,就和右边指针指向的数字交换,如果nums[i] == 1,i++,继续遍历。
3. 这样就把最小的数全部移动到左边,把最大的数全部移动到了右边
代码(python实现)
class Solution(object): def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ if nums is None or len(nums) <= 1 : return pl = 0 pr = len(nums) - 1 i = 0 while(i <= pr): if nums[i] == 0: self.swap(nums, i, pl) #此时nums[i]必为1,因此i+1 pl += 1 i += 1 elif nums[i] == 1: i += 1 elif nums[i] == 2: self.swap(nums, i, pr) #此时nums[i]不确定,因此需要在新的一轮中判断nums[i] pr -= 1 def swap(self, nums, i, j): temp = nums[i] nums[i] = nums[j] nums[j] = temp
注意:写完代码用测试用例检验