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--;
                }
            }
        }
    };
  • 相关阅读:
    字符串处理类
    PageHelper
    JavaScriptPlus操作类
    Http 数据操作
    解压 压缩 C#
    验证码生成 C#
    MySecurity(安全类)
    博客搬迁至wordpress站点
    我的前端MVC之路
    三个css3趣玩小试
  • 原文地址:https://www.cnblogs.com/li-daphne/p/5618462.html
Copyright © 2011-2022 走看看