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 }
  • 相关阅读:
    CBR(基于案例的推理)的产生和Roger Schank=Schank教授在他的著作中提出了以“记忆组织包"
    php 设计模式
    php 常用资源
    自然语言处理著作或期刊名称2
    北京师范大学语言学及应用语言学研究生培养方案
    !!! Analysis & Design 很好的汇总+zcl的 UML 体会
    睡眠的方法
    !!!【php100教程】
    机器翻译和自然语言信息处理专业硕士研究生培养方案
    愧薪
  • 原文地址:https://www.cnblogs.com/zhaolizhen/p/SortColors.html
Copyright © 2011-2022 走看看