• 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++]);
    	}
    }
    
  • 相关阅读:
    阻止事件的默认行为,例如click <a>后的跳转~
    阻止事件冒泡
    IE67不兼容display:inline-block,CSS hack解决
    IE678不兼容CSS3 user-select:none(不可复制功能),需要JS解决
    JS数组常用方法总结
    json 只能用 for-in 遍历
    用实例的方式去理解storm的并发度
    OpenLDAP 搭建入门
    kafka api的基本使用
    kafka基本介绍
  • 原文地址:https://www.cnblogs.com/ZhongliangXiang/p/7490377.html
Copyright © 2020-2023  润新知