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++;
                }
            }
        }
    };
  • 相关阅读:
    hadoop之 mr输出到hbase
    北美IT公司大致分档
    推荐系统(协同过滤,slope one)
    机器学习的常见面试问题
    关联规则之Aprior算法(购物篮分析)
    Python的Set和List的性能比较 + 两者之间的转换
    Python 集合set添加删除、交集、并集、集合操作符号
    3.算法-二叉树遍历
    1.系统设计-概要
    2算法-二分查找
  • 原文地址:https://www.cnblogs.com/vincently/p/4781010.html
Copyright © 2011-2022 走看看