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

    题目描述:  

      给定一个数组arr,和一个数num,请把小于num的数放在数组的左边,等于num的数放在数组的中间,大于num的数放在数组的右边。要求额外空间复杂度O(1),时间复杂度O(N)

    解题思路:

      使用两个指针:p1,p2

      p1 = -1;  //左指针,在p1左边并含p1的所有数都<num

      p2 = N ; //右指针,p2=N在p2的右边含p2的所有数都大于num

      然后比较arr与num的值,并与相应的p1,p2的位置交换

    代码实现:  

     1 #include <iostream>
     2 
     3 using namespace std;
     4 
     5 
     6 void swap(int& a, int &b)
     7 {
     8     int temp;
     9     temp = a;
    10     a = b;
    11     b = temp;
    12 }
    13 
    14 //记住,单次遍历n(n << N)次数组的时间复杂度 = n*O(N) == O(N)
    15 template<class T>//目前我只想到了使用模板来实现引用数组,其他的引用方法都报错了。
    16 void Test(T& array , const int num)
    17 {
    18     int N, p1, p2;//两个指针
    19     p1 = -1;//左指针,在p1左边并含p1的所有数都<num
    20     p2 = N = sizeof(array) / sizeof(array[0]);//右指针,p2=N在p2的右边含p2的所有数都大于num
    21     for (int i = 0; i != p2; )
    22     {
    23         if (array[i] < num)
    24             swap(array[++p1], array[i++]);
    25         else if (array[i] > num)
    26             swap(array[--p2], array[i]);
    27         else
    28             ++i;
    29 
    30     }
    31 
    32 }
    33 
    34 void Heland()
    35 {
    36     int arr[] = { 1, 5,7,4,6,4,2,9 };    
    37     Test(arr, 4);
    38     for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); ++i)
    39         cout << arr[i] << "  ";
    40     cout << endl << "**************************" << endl;
    41 }

      

  • 相关阅读:
    javascript实现非递归--归并排序
    javascript实现二分查找
    深入javascript作用域链到闭包
    c++学习笔记2--constexpr,类型别名,auto
    用 Numba 加速 Python 代码
    Django1和2的区别
    Git的使用
    文件锁fcntl
    Https原理
    Flask-Login
  • 原文地址:https://www.cnblogs.com/zzw1024/p/10987751.html
Copyright © 2011-2022 走看看