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++]);
    	}
    }
    
  • 相关阅读:
    js 各种常用js验证
    js url校验
    最近遇到的技术问题
    a标签的target的四个值
    新系统用到的新知识
    7 天打造前端性能监控系统
    前端必读:浏览器内部工作原理
    怎么判断ThreadPool线程池里的任务都执行完毕
    docker 在window 10 专业版的安装 && .net core 在docker的部署
    .net core 中后台获取前台 数据(post)的方法
  • 原文地址:https://www.cnblogs.com/ZhongliangXiang/p/7490377.html
Copyright © 2011-2022 走看看