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 }
  • 相关阅读:
    咖啡生活-享受慵懒的午后时光
    窗体皮肤实现
    编译树莓派2代B型OpenWrt固件实现无线路由器及nodogsplash认证功能
    通过hook实现禁止shift+delete快捷键
    c++ Qt向PHP接口POST文件流
    Qt for Android开发总结
    A previous installation of Qt5 Visual Studio Add-in was detected. Please uninstall it before running this installer解决办法
    windows下Qt5.1 for android开发环境配置
    Qt+mpg123+openal播放MP3流
    RTC搭建android下三层应用程序访问服务器MsSql-客户端
  • 原文地址:https://www.cnblogs.com/zhaolizhen/p/SortColors.html
Copyright © 2011-2022 走看看