首页 > 其他 > 详细

leetcode 75颜色分类

时间:2019-05-27 17:39:32      阅读:132      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

两趟扫描,由于排序变量的特殊性,使用计数排序方法可以明显降低至O(n)time O(n) space

关于计数排序:https://mp.weixin.qq.com/s/WGqndkwLlzyVOHOdGK7X4Q

class Solution {
public:
    void sortColors(vector<int>& nums) {
        if(nums.size()==0) return;
        int len=nums.size();
        vector<int> arr(3,0);
        for(int num:nums)
            arr[num]++;
        int index=0;
        for(int i=0;i<arr.size();i++){
            int k=arr[i];
            while(k--){
                nums[index++]=i;
            }
        }
    }
};

 使用3个变量一趟扫描O(1) space O(n) time

/**
使用3个变量来分别表示3个颜色;
**/

class Solution {
public:
    void sortColors(vector<int>& nums) {
        if(nums.size()==0) return;
        int len=nums.size();
        int L=0,M=0,H=len-1;
        while(M<=H){
            if(nums[M]==1){
                M++;continue;
            }
            if(M<=H&&nums[M]==0){
                swap(nums[M],nums[L]);
                L++;M++;
            }
            if(M<=H&&nums[M]==2){
                swap(nums[M],nums[H]);
                H--;
            }
        }
    }
};

 具体实现过程参见:https://leetcode.com/problems/sort-colors/discuss/26474/Sharing-C%2B%2B-solution-with-Good-Explanation

技术分享图片

 

leetcode 75颜色分类

原文:https://www.cnblogs.com/joelwang/p/10931303.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!