|
| 1 | +""" |
| 2 | + |
| 3 | +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. |
| 4 | + |
| 5 | +Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. |
| 6 | + |
| 7 | +Note: You are not suppose to use the library's sort function for this problem. |
| 8 | + |
| 9 | +Example: |
| 10 | + |
| 11 | +Input: [2,0,2,1,1,0] |
| 12 | +Output: [0,0,1,1,2,2] |
| 13 | +Follow up: |
| 14 | + |
| 15 | +A rather straight forward solution is a two-pass algorithm using counting sort. |
| 16 | +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. |
| 17 | +Could you come up with a one-pass algorithm using only constant space? |
| 18 | + |
| 19 | + |
| 20 | +给一个放置了颜色的数组,里面包含三种颜色分别为 红 白 蓝,用 0 1 2 表示,它们在数组中是无序的,现在要把它们进行排序。 |
| 21 | + |
| 22 | +要求是: |
| 23 | +原数组排序。 |
| 24 | + |
| 25 | +进阶条件是: |
| 26 | +1. one-pass. |
| 27 | +2. 使用常数空间。O(1)空间。 |
| 28 | + |
| 29 | +直接.sort排序是作弊行为。 |
| 30 | + |
| 31 | +进阶条件里给出一个直接的方法: |
| 32 | + |
| 33 | +过一遍,分别记录出 0 1 2 的个数,然后按个数将它们分别替换。 |
| 34 | + |
| 35 | +这样做虽然是 O(1) 空间,不过不是 one-pass。 |
| 36 | + |
| 37 | +自己的思路: |
| 38 | + |
| 39 | +由于只有三种要排序的,以1为中心点,那么出现0放到最左边即可,出现2放到最右边即可。 |
| 40 | + |
| 41 | +那么设置一个指针。从 0 开始,若为0则将它从原数组弹出,然后放到0的位置,若是2则放到末尾。若是1则不变。 |
| 42 | + |
| 43 | +1. 出现0和1的情况都将index向前推进1,2的话则不推进。 |
| 44 | + |
| 45 | +这样做是one-pass,O(1),符合进阶条件。缺点是 insert和pop都是 O(n) 时间复杂度的算法。使用deque会快一些,现在也可以。 |
| 46 | + |
| 47 | + |
| 48 | +beat: |
| 49 | +64% |
| 50 | + |
| 51 | +测试地址: |
| 52 | +https://leetcode.com/problems/sort-colors/description/ |
| 53 | + |
| 54 | +""" |
| 55 | +class Solution(object): |
| 56 | + def sortColors(self, nums): |
| 57 | + """ |
| 58 | + :type nums: List[int] |
| 59 | + :rtype: void Do not return anything, modify nums in-place instead. |
| 60 | + """ |
| 61 | + |
| 62 | + index = 0 |
| 63 | + times = 0 |
| 64 | + length = len(nums) |
| 65 | + |
| 66 | + for i in range(length): |
| 67 | + if nums[index] == 0: |
| 68 | + x = nums.pop(index) |
| 69 | + nums.insert(0, x) |
| 70 | + index += 1 |
| 71 | + elif nums[index] == 2: |
| 72 | + x = nums.pop(index) |
| 73 | + nums.append(x) |
| 74 | + else: |
| 75 | + index += 1 |
0 commit comments