zoukankan      html  css  js  c++  java
  • 荷兰国旗问题

    描述:

    将三种颜色作为012,要求将无序数组排为有序。

    思路:

    1.遍历,记录0,1,2的个数,然后重写数组。O(N)的时间复杂度。需要额外空间
    2.采用交换的思想,遍历数组,将无序的数字交换到前后。O(N)的时间复杂度。空间复杂度O(1)。

    代码:

    public void ThreeSort(int[] arr,int len)
        {
            int begin=0;
            int end=len-1;
            int current=0;
            while(current<=end) //从交换来的棋子是0,又恰好current==end,此时还要判断。
            {
                if(arr[current]==0)
                {
                    SWAP(arr,begin,current);
                    begin++;
                    current++;  //从左边开始移动的能保证current左方的值一定是0;
                }
                else if(arr[current]==1)
                {
                    current++;
                }
                else if(arr[current]==2)
                {
                    SWAP(arr,end,current);
                    end--;   //交换过来的可能是0,current不能移动
                }
    
            }
        }
    
  • 相关阅读:
    CCCC练习即感
    1003 我能通过
    录制开讲啦杂感
    OOP第三次上机
    关于C++随机函数
    蓝桥杯杂感。
    CF502C The Phone Number
    It's a secret
    2017-06-22
    2017-05-12
  • 原文地址:https://www.cnblogs.com/void-lambda/p/12457205.html
Copyright © 2011-2022 走看看