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++]);
    	}
    }
    
  • 相关阅读:
    Java程序设计作业02
    Java程序设计作业01
    DS博客作业05
    DS博客作业04
    DS博客作业03
    DS博客作业02
    DS博客作业01
    C博客作业06
    C博客作业05
    C语言——数组作业批改
  • 原文地址:https://www.cnblogs.com/ZhongliangXiang/p/7490377.html
Copyright © 2011-2022 走看看