美文网首页
Leetcode[75] Sort Colors

Leetcode[75] Sort Colors

作者: 耳可黄 | 来源:发表于2017-09-06 07:33 被阅读0次
    1. Time O(n), Space O(n)
    class Solution {
    public:
        void sortColors(vector<int>& nums) {
            int r = 0, w = 0, b = 0;
            for(int i: nums) {
                if(i == 0) r++;
                else if (i == 1) w++;
                else b++;
            }
            vector<int> sorted;
            for(int i = 0; i < r; i++) {
                sorted.push_back(0);
            }
            for(int i = 0; i < w; i++) {
                sorted.push_back(1);
            }
            for(int i = 0; i < b; i++) {
                sorted.push_back(2);
            }
            nums.swap(sorted);
        }
    };
    
    1. O(n) O(1)
    class Solution {
    public:
        void sortColors(vector<int>& nums) {
            if(nums.size() <= 1) return;
            int r = 0, w = 0, b = nums.size()-1;
            while(w <= b) {
                if(nums[w] == 0) {
                    nums[w] = nums[r];
                    nums[r] = 0;
                    w++;
                    r++;
                } else if(nums[w] == 1) {
                    w++;
                } else {
                    nums[w] = nums[b];
                    nums[b] = 2;
                    b--;
                }
            }
        }
    };
    

    相关文章

      网友评论

          本文标题:Leetcode[75] Sort Colors

          本文链接:https://www.haomeiwen.com/subject/cskmjxtx.html