Leetcode 75. Sort Colors

文章作者:Tyan
博客:noahsnail.com  |  CSDN  | 

1. Description

Sort Colors

2. Solution

  • Two-pass
class Solution {
public:
    void sortColors(vector& nums) {
        int left = 0;
        int right = nums.size() - 1;
        int red = 0;
        int white = 0;
        int blue = 0;
        for(int i = 0; i < nums.size(); i++) {
            if(nums[i] == 0) {
                red++;
            }
            else if(nums[i] == 1) {
                white++;
            }
            else {
                blue++;
            }
        }
        for(int i = 0; i < red; i++) {
            nums[i] = 0;
        }
        for(int i = red; i < red + white; i++) {
            nums[i] = 1;
        }
        for(int i = red + white; i < nums.size(); i++) {
            nums[i] = 2;
        }
    }
};
  • One-pass, no swap
class Solution {
public:
    void sortColors(vector& nums) {
        int low = 0;
        int mid = 0;
        int high = 0;
        for(int i = 0; i < nums.size(); i++) {
            if(nums[i] == 0) {
                nums[high++] = 2;
                nums[mid++] = 1;
                nums[low++] = 0;
            }
            else if(nums[i] == 1) {
                nums[high++] = 2;
                nums[mid++] = 1;
            }
            else {
                nums[high++] = 2;
            }
        }
    }
};
  • One-pass, swap
class Solution {
public:
    void sortColors(vector& nums) {
        int left = 0;
        int mid = 0;
        int high = nums.size() - 1;
        while(mid <= high) {
            if(nums[mid] == 0) {
                swap(nums[mid], nums[left]);
                left++;
                mid++;
            }
            else if(nums[mid] == 2) {
                swap(nums[mid], nums[high]);
                high--;
            }
            else {
                mid++;
            }
        }
    }
private:
    void swap(int& a, int& b) {
        int temp;
        temp = a;
        a = b;
        b = temp;
    }
};

Reference

  1. https://leetcode.com/problems/sort-colors/description/

你可能感兴趣的:(Leetcode 75. Sort Colors)