LeetCode Sort Problem || Sort Colors

来源:互联网 发布:linux查看剩余磁盘空间 编辑:程序博客网 时间:2024/05/22 07:03

题目描述

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.
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?


解题思路

这个题目只是一个很简单的排序题,题目要求不能用任何排序函数,那就自己写咯~也没有限制时间复杂度之类的,简单一个冒泡完事。这也就是follow up里说的one-pass algorithm。另一个思路是看到题目中的提示,two-pass algorithm,从vector尾部读元素,并分别记下0,1,2的数目,读一个pop一个,然后再重新按个数push进原来的vector中。
这道题在LeetCode sort problem中是medium,只要知道排序算法,其实非常简单啦!

方法一

class Solution {public:    void sortColors(vector<int>& nums) {        int temp;        for(int i = 0; i < nums.size(); i++){            for(int j = nums.size() - 1; j > i; j--){                if(nums[j] < nums[j - 1]){                    temp = nums[j];                    nums[j] = nums[j - 1];                    nums[j - 1] = temp;                }            }        }    }};

方法二

class Solution {public:    void sortColors(vector<int>& nums) {        int num0 = 0, num1 = 0, num2 = 0;        while(!nums.empty()){            if(nums.back() == 0){                num0++;            }            else if(nums.back() == 1){                num1++;            }            else if(nums.back() == 2){                num2++;            }            nums.pop_back();        }        for(int i = 0; i < num0; i++) nums.push_back(0);        for(int i = 0; i < num1; i++) nums.push_back(1);        for(int i = 0; i < num2; i++) nums.push_back(2);    }};
0 0
原创粉丝点击