zoukankan      html  css  js  c++  java
  • leetcode:Sort Colors (面试 笔试)

    Question:

    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.

    Follow up:
    A rather straight forward solution is a two-pass algorithm using counting sort.
    First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.

    Could you come up with an one-pass algorithm using only constant space?

    问题:给定一个长度为n的数组,里边有red,white,blue这些颜色,把他们进行排序,以便让他们相邻的元素毗邻,顺序为red,white,blue,在这里,用0,1,2分别代表red,white,和blue三种颜色。不能使用排序的类库,要求在O(N)时间复杂度,O(1)的空间复杂度完成排序。

    思路:借鉴快速排序的思想,或者《剑指Offer》中的一个题(对于一个数组,把奇数放在偶数前面)的思想,设置两个指针,一个从前向后扫描(i),一个从后向前扫描(j),i指向的数如果等于0,则继续往后,知道它指向的不为0,对于j指向的数不等于0继续往前,直到等于0,这样在第一个循环完成,0已经排好序,下面再对1和2排序,同样的道理。具体看下边代码:

     1 void swap(int &a, int&b)
     2 {
     3     int temp = a;
     4     a = b;
     5     b = temp;
     6 }
     7 void sortColors(int A[], int n) 
     8 {
     9     int i = 0;
    10     int j = n - 1;
    11     int k = n - 1;
    12     int count = 0;
    13     for (int i = 0; i < n;i++)
    14     if (A[i] == 0)
    15         count++;//求出0的个数
    16     while (i < j){//循环完成后,0已经就位
    17         while (i < j&&A[i] == 0) i++;
    18         while (i < j&&A[j] != 0)j--;
    19         swap(A[i++], A[j--]);
    20     }
    21     i = count;
    22     while (i < k){//循环完成 1已经就位 相应2也应该就位
    23         while (i < k&&A[i] == 1)i++;
    24         while (i < k&&A[k] != 1)k--;
    25         swap(A[i++], A[k--]);
    26     }
    27 }
  • 相关阅读:
    性能测试流程
    N种自动化测试框架(包含自动化和性能,总有一款适合你)
    自动化测试框架:jmeter + maven+ jenkins
    oracle中删除表:drop、delete、truncate
    SpringBoot开发mockserver及生成swagger接口文档
    五步法颈椎病自我按摩图解
    自动化必备:自动化持续集成环境搭建(上):git + maven + jenkins
    玩转jmeter:beanshell必备技能
    EFK-2:ElasticSearch高性能高可用架构
    MySQL5.7之在线DDL不会锁表
  • 原文地址:https://www.cnblogs.com/zhaolizhen/p/SortColors.html
Copyright © 2011-2022 走看看