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.

    分析

    实际上就是使用快排去做,升序
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    class Solution {
    public:
        void sortColors(vector<int>& nums) {
            sortHelper(nums, 0, nums.size() - 1);
        }
         
        void sortHelper(vector<int> & nums, int left, int right){
            if(left >= right) return;
            int i = left, j = right;
            int key = nums[(left + right) / 2];
            while(i <= j){
                while(i <= j && nums[i] < key) ++i;
                while(i <= j && nums[j] > key) --j;
                if(i <= j){
                    int tmp = nums[i];
                    nums[i++] = nums[j];
                    nums[j--] = tmp;
                }
            }
            sortHelper(nums, left, j);
            sortHelper(nums, i, right);
        }
    };




  • 相关阅读:
    html5-特殊符号的使用
    html5-表格
    html5-列表
    html5-绝对路径/相对路径
    html5-嵌入图片
    html5-超级链接
    html5-常用的文本元素
    html5-了解元素的属性
    Scanner类throwFor(Unknown Source)及跳过下一个扫描器分析
    有关HashMap的一些问题及解答
  • 原文地址:https://www.cnblogs.com/zhxshseu/p/f0795ce095a6d089dbeaa4eb320180f4.html
Copyright © 2011-2022 走看看