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 supposed to use the library's sort function for this problem.

    这题就是想把乱序的[2 2 1 0 1 1 0 2]排列成有序的[0 0 1 1 1 2 2 2].

    方法一:两趟循环,第一趟数0,1,2的个数,第二趟修改数组A, 思想简单且无编程难度.
    (O(2n)) time, (O(1)) extra space.

    // two-pass algorithm
    // [ 2 2 1 0 1 1 0 2]
    void sortColors(vector<int>& A) {
    	int c_0 = 0, c_1 = 0;
    
    	for (int i = 0; i < A.size(); i++)
    		if (A[i] == 0) c_0++;
    		else if (A[i] == 1) c_1++;
    
    	for (int i = 0; i < A.size(); i++)
    		if (i < c_0) A[i] = 0;
    		else if (i >= c_0 && i < (c_1 + c_0)) A[i] = 1;
    		else A[i] = 2;
    }
    

    方法二,人家的想法了,就是扫描数组,发现2就送入队尾方向,发现0就送队首方向,最后1自然就在中间,就排好了.这方法编程不容易.

    设定 zero = 0, sec = A.size()-1 两个指针.
    若 A[i] = 2, swap(A[i], A(sec--));
    若 A[i] = 0, swap(A[i], A(zero++));
    
    // one-pass algorithm
    // [ 2 2 1 0 1 1 0 2]
    void sortColors(vector<int>& A) {
    	int zero = 0, sec = A.size() - 1;
    	for (int i = 0; i <= sec; i++) {
    		while (A[i] == 2 && i < sec) swap(A[i], A[sec--]);
    		while (A[i] == 0 && i > zero) swap(A[i], A[zero++]);
    	}
    }
    
  • 相关阅读:
    Linux服务器程序规范化
    Linux I/O函数
    IP协议详解
    Linux C++ 连接 MySQL
    I/O复用
    Linux网络编程基础API
    TCP协议详解
    React源码解携(二): 走一趟render流程
    记账项目 webpack优化
    前端监控系统博客总结
  • 原文地址:https://www.cnblogs.com/ZhongliangXiang/p/7490377.html
Copyright © 2011-2022 走看看