• Leetcode OJ: Sort Color


    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?

    第一反应就是排序,但题目不能用,然后就是hash,也不能用。接着就想到类似选择排序的思路了。

    i, k表示开头与结尾的下标,然后j为当前扫描点的下标,判断为0则放i中,i++,判断为2则放k中,k++,其它j++。

    由于LZ比较心急,写的时候以为当前扫描点与交换的点是可以一起换,所以写成了swap(A[i++], A[j++])类似这样的形式,然后就果断出错了。

    这里需要注意的是,每扫描一次,只改变一个下标(i 或 j 或 k),不要太贪心了!

    代码如下:

     1 class Solution {
     2 public:
     3     void sortColors(int A[], int n) {
     4         int i = 0, k = n - 1;
     5         int j = i;
     6         while (j <= k) {
     7             if (A[j] == 0) {
     8                 if (j > i)
     9                     swap(A[i++], A[j]);
    10                 else {
    11                     ++i;
    12                     ++j;
    13                 }
    14             } else if (A[j] == 2) {
    15                 if (j < k) {
    16                     swap(A[j], A[k--]);
    17                 } else {
    18                     break;
    19                 }
    20             } else
    21                 ++j;
    22         }
    23     }
    24 };
     
  • 相关阅读:
    Linux 10字符串命令病毒的处理记录
    Spring的核心模块解析
    干货 | 教你如何监控 Java 线程池运行状态
    关于Spring事物的面试题
    Integer、new Integer() 和 int 比较的面试题
    性能监控工具-JDK命令行工具
    JVM调优总结 -Xms -Xmx -Xmn -Xss
    JVM系列三:JVM参数设置、分析
    JVM—内存溢出、OutOfMemoryError、StackOverflowError
    7种垃圾收集器
  • 原文地址:https://www.cnblogs.com/flowerkzj/p/3644782.html
Copyright © 2020-2023  润新知