Sort Colors

来源:https://leetcode.com/problems/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.

 

选择排序(Selection sort)是一种简单直观的排序算法。它的工作原理如下。首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。 --维基百科  https://zh.wikipedia.org/wiki/选择排序

选择排序的复杂度(非本题复杂度):

时间复杂度,平均O(n^2),最好O(n^2),最坏O(n^2)

空间复杂度,辅助存储O(1)

稳定性,不稳定

 

方法:应用选择排序的思想,将最小元素(0)从起始位置开始排,将最大元素(2)从末尾位置开始排,剩下的1自然就排好了

Java

 1 class Solution {
 2     public void sortColors(int[] nums) {
 3         int zeroPos = 0, twoPos = nums.length-1, tmp = 0;
 4         for(int i=0; i<=twoPos; i++) {
 5             if(nums[i] == 0) {
 6                 tmp = nums[i];
 7                 nums[i] = nums[zeroPos];
 8                 nums[zeroPos] = tmp;
 9                 zeroPos++;
10             }
11             if(nums[i] == 2 && i < twoPos) {
12                 tmp = nums[i];
13                 nums[i] = nums[twoPos];
14                 nums[twoPos] = tmp;
15                 twoPos--;
16                 i--;
17             }
18         }
19     }
20 }

另一种神奇的方法,本质是记录了0的个数(r),0和1的个数(w),0、1和2的总个数(b)

Python

 1 class Solution(object):
 2     def sortColors(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: void Do not return anything, modify nums in-place instead.
 6         """
 7         r, w, b = 0, 0, 0
 8         for i in range(len(nums)):
 9             if nums[i] == 0:
10                 nums[b] = 2
11                 nums[w] = 1
12                 nums[r] = 0
13                 b += 1
14                 w += 1
15                 r += 1
16             elif nums[i] == 1:
17                 nums[b] = 2
18                 nums[w] = 1
19                 b += 1
20                 w += 1
21             else:
22                 nums[b] = 2
23                 b += 1

 

posted @ 2017-09-19 21:24  HitAnyKey  阅读(128)  评论(0编辑  收藏  举报