79-Sort Colors

来源:互联网 发布:财智软件 倒闭 编辑:程序博客网 时间:2024/06/06 12:34
  1. Sort Colors
    Total Accepted: 99361 Total Submissions: 285131 Difficulty: Medium
    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?

题意:对rgb序列排序,相当于对数组排序,只不过元素取值集合为{0,1,2}
用计数排序肯定是可以的,不过需要扫描两遍
但题目要求只能扫描一遍

所以还是有点难度的:
思路:由于只有三种取值,那么只要我们排定了最大和最小的2种元素,剩下的元素就自然在确定的位置了

class Solution {public:    void sortColors(vector<int>& nums) {        int n=nums.size();        int red=0,blue=n-1;  //设定头尾指针,存放0和2        for(int i=0;i<=blue;){//从头至尾扫描            if(nums[i]==2)  // 遇到2则放到后面确定位置,同时对i位置新元素进行下一轮                swap(nums[i],nums[blue--]);            else if(nums[i]==0)swap(nums[i++],nums[red++]);//遇到0放到前面,检测下一元素            else ++i; //如果不是指定值0或2,不用管,跳到下一元素        }    }};
0 0
原创粉丝点击