zoukankan      html  css  js  c++  java
  • [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++;
                }
            }
        }
    };
  • 相关阅读:
    边框的各种样式
    内容溢出显示省略号
    UNIAPP开发注意事项
    css文本的三条线 删除线 下划线 上划线
    防抖截流
    浏览器窗口改变触发的函数
    ES5数组方法
    弹性布局
    ubuntu16.04 安装adb
    git clone
  • 原文地址:https://www.cnblogs.com/vincently/p/4781010.html
Copyright © 2011-2022 走看看