美文网首页
leetcode 75. 颜色分类

leetcode 75. 颜色分类

作者: Source_Chang | 来源:发表于2020-10-31 18:13 被阅读0次

leetcode

  1. 数组标记法
    C++:
class Solution {
public:
    void sortColors(vector<int>& nums) {
        
        std::vector<int> arrMarks = std::vector<int>(3, 0);
        for ( int i = 0; i < nums.size(); ++i ) {

            int value = nums[i];
            if ( value < arrMarks.size() ) {

                arrMarks[value] += 1;
            }
        }

        std::vector<int> sortedNums;
        for ( int i = 0; i < arrMarks.size(); ++i ) {

            for ( int j = 0; j < arrMarks[i]; ++j ) {

                sortedNums.push_back(i);
            }
        }

        nums = sortedNums;
    }
};
  1. 三指针
    C++:
class Solution {
public:
    void sortColors(vector<int>& nums) {
        
        int left = 0;
        int right = nums.size() - 1;
        int current = left;
        while ( current <= right ) {

            if ( nums[current] == 0 && current >= left ) {

                std::swap(nums[current], nums[left]);
                ++left;

            } else if ( nums[current] == 2 ) {

                std::swap(nums[current], nums[right]);
                --right;

            } else {

                ++current;
            }
        }
    }
};
  1. 双指针法
    C++:
class Solution {
public:
    void sortColors(vector<int>& nums) {
        
        int left = 0;
        int right = nums.size() - 1;
        for ( int i = 0; i <= right; ++i ) {

            while ( i <= right && nums[i] == 2 ) {

                std::swap(nums[i], nums[right]);
                --right;
            }

            if ( nums[i] == 0 ) {

                std:;swap(nums[i], nums[left]);
                ++left;
            }
        }
    }
};

相关文章

网友评论

      本文标题:leetcode 75. 颜色分类

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