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++;
                }
            }
        }
    };
  • 相关阅读:
    telnet发邮件
    怎样接收电子邮件(POP3协议简介)(转载,写的很简洁)
    总结:string,char*,CString,int,WCHAR*之间的相互转换:
    文件查找
    SOAP消息机制简介
    jQuery 万能的选择器 NO.1
    数据库通用操作类
    jQuery (三) 管理jQuery包装集
    WebService Learning
    使用JQuery读取XML文件数据
  • 原文地址:https://www.cnblogs.com/vincently/p/4781010.html
Copyright © 2011-2022 走看看