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++;
                }
            }
        }
    };
  • 相关阅读:
    javaweb 乱码总结
    android面试
    如何截取url中的各个参数?
    Spring2.0集成Quartz1.5.2调度框架
    关于使用HttpSessionBindingListener获取在线用户数,同一用户登陆一次
    struts项目中添加的jar包
    日期和时间的正则表达式
    常用的正则表达式
    关于在页面上执行sql语句
    失败的31种原因 程序员们占了几种
  • 原文地址:https://www.cnblogs.com/vincently/p/4781010.html
Copyright © 2011-2022 走看看