zoukankan      html  css  js  c++  java
  • 75. 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

    ==========

    有三种颜色的物体若干,颜色分别是red,waite,blue,分别使用数组0,1,2来表示.

    要求是:将这些物体按照颜色red,waite,blue排序.

    =======

    思路:

    采用快速排序的思路:

    begin:指向将要排序为red(0)的位置

    end:指向将要排序为blue(2)的位置

    curr:遍历指针,

     如果当前元素为0,则和begin位置swap,通知begin++,curr++

     如果当前元素为1,curr++

     如果当前元素为2,则和end位置swap,但是curr元素不能增加,end--

    ====

    code:

    class Solution {
    public:
        void sortColors(vector<int>& nums) {
            int n = nums.size();
            int curr,begin,end;
            curr = begin = 0;
            end = n-1;
            while(curr<=end){
                if(nums[curr]==0){
                    swap(nums[begin++],nums[curr++]);
                }else if(nums[curr]==1){
                    curr++;
                }else if(nums[curr]==2){
                    swap(nums[end],nums[curr]);
                    end--;
                }
            }
        }
    };
  • 相关阅读:
    Python元类
    Python接口与归一化设计
    如何使用yum下载rpm包
    浅谈Python的with语句
    搞懂了这几点,你就学会了Web编程
    网络虚拟化技术大观
    Python装饰器
    Kubernetes配置Ceph RBD StorageClass
    编译Kubelet二进制文件
    记一次虚拟机无法挂载volume的怪异问题排查
  • 原文地址:https://www.cnblogs.com/li-daphne/p/5618462.html
Copyright © 2011-2022 走看看