[Leetcode] 75. Sort Colors 解题报告

来源:互联网 发布:淘宝美工岗位 编辑:程序博客网 时间:2024/06/03 21:33

题目

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.

click to show follow up.

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 an one-pass algorithm using only constant space?

思路

发现自己原来写的代码就是两遍扫描,感觉好low。一遍扫描需要维持三个关键索引:1)left:left左边的值都应该是0;2)right:right右边的值都应该是2;3)i:当前的扫描位置。每次扫描碰到0,则和left交换位置并且left右移一位;碰到2,则和right交换位置并且right左移一位(注意此时扫描位置i不能前进,因为我们不知道从right处交换过来的值是0还是1)。

代码

class Solution {public:    void sortColors(vector<int>& nums) {        if(nums.size() == 0)            return;        int i = 0, left = 0, right = nums.size() - 1;        while(i <= right)          {              if(nums[i] == 2)                  swap(nums[i], nums[right--]);              else               {                  if(nums[i] == 0)                      swap(nums[left++], nums[i]);                  i++;              }          }      }};

0 0