• [LeetCode] Sort Colors


    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.

      

      将乱序的红白蓝三色小球排列成同颜色在一起的小球组(按照红白蓝排序),这个问题称为荷兰国旗问题。这是因为我们可以将红白蓝三色小球想象成条状物,有序排列后正好组成荷兰国旗。我们用0表示红球,2为篮球,1为白球。

      解答:这个问题典型地利用快排中partition过程。不过,要用三个指针,一前begin,一中current,一后end,begin与current都初始化指向数组首部,end初始化指向数组尾部。

        1. current遍历整个序列,current指1时,不交换,current++

        2. current指0时,与begin交换,而后current++,begin++

        3. current指2时,与end交换,而后,current不动,end--

    class Solution {
    public:
        void sortColors(vector<int>& nums) {
            if(nums.empty()) return;
            
            int beg = -1;
            int end = nums.size();
            int curr = 0;
            
            while (curr < end) {
                if (nums[curr] == 0) {
                    swap(nums[curr], nums[++beg]);
                    curr++;
                } else if (nums[curr] == 2) {
                    swap(nums[curr], nums[--end]);
                } else {
                    curr++;
                }
            }
        }
    };
  • 相关阅读:
    持续集成
    持续集成
    持续集成
    持续集成
    持续集成
    持续集成
    CuDNNLSTM: UnknownError: Fail to find the dnn implementation
    Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'
    django nginx uwsgi 502 Gateway
    ubuntu nginx 启动多个Django项目
  • 原文地址:https://www.cnblogs.com/vincently/p/4781010.html
Copyright © 2020-2023  润新知