問題1:
給定一個數組arr,和一個數num,請把小於等於num的數放在數
組的左邊,大於num的數放在數組的右邊。
要求額外空間複雜度O(1),時間複雜度O(N)
問題2(荷蘭國旗問題)
給定一個數組arr,和一個數num,請把小於num的數放在數組的
左邊,等於num的數放在數組的中間,大於num的數放在數組的
右邊。
要求額外空間複雜度O(1),時間複雜度O(N)
求解答案:
#include <iostream> //題目1 void func(int *a,int b) { int p=-1; for (int i = 0; i <10 ; i++) { if (a[i]<b ) { std::swap(a[p+1],a[i]); p++; } } } //題目2荷蘭國旗問題func1 void func1(int *a, int b) { int less=-1; int num=11; int more=12; int current=0; while (current<more) { if (a[current]<b) { std::swap(a[current++],a[++less]); } else if (a[current]>b) { std::swap(a[current ],a[more-1]); more--; } else if (a[current]=b) { current++; } // else if (a[current]=b) // { // current++; // } std::cout<<"less:"<<less<<std::endl; std::cout<<"more:"<<more<<std::endl; } } int main() { int array[]={3,11,5,7,9,9,9,2,33,44,12,45}; // func(array,9); // for (int i = 0; i <10 ; i++) { // std::cout<<array[i]; // } // std::cout<<std::endl; std::cout<<"------------------------------------"<<std::endl; func1(array,9); for (int i = 0; i <12 ; i++) { std::cout<<array[i]<<" "; } std::cout<<std::endl; return 0; }