標籤:style blog http color os 2014
由於兩個數組,一比較就會出現兩次for迴圈,所以我能想到的就是組合求出現次數,這樣子,就不會出現兩次for迴圈,上代碼,希望有看到的提出更好的方法
1 #include <iostream> 2 using namespace std; 3 4 void printarray(int *arr, int size) 5 { 6 if (arr == nullptr) 7 { 8 return; 9 }10 cout << endl;11 for (int i = 0; i < size; i++)12 {13 cout << arr[i] << " ";14 }15 cout << endl;16 }17 18 int main()19 {20 int a[] = {1, 2, 3, 4, 5};21 int b[] = {1, 4, 5, 6, 9, 8};22 int i = 0, j = 0;23 24 int counta = sizeof(a)/sizeof(int); //a數組長度25 int countb = sizeof(b) / sizeof(int); //b數組長度26 27 cout << "a數組元素:";28 printarray(a, counta);29 30 cout << "b數組元素:";31 printarray(b, countb);32 33 int *c = new int[counta + countb]; //用於儲存a、b組合後的數組34 35 //將a數組存入c數組中36 for (i = 0; i < counta; i++)37 {38 c[i] = a[i];39 }40 //將b數組存入c數組中,緊接著a數組裡的元素41 for (i = counta, j = 0; i < counta + countb/*j < countb*/; i++,j++)42 {43 c[i] = b[j];44 }45 46 //求出兩個數組中最大的那個值47 int maxnum = c[0];48 for (i = 0; i < counta + countb; i++)49 {50 if (maxnum < c[i])51 {52 maxnum = c[i];53 }54 }55 56 //將數組裡的元素值作為d數組的下標,這樣,出現這個數字一次,57 // d數組相應下標的元素值就加一,最後判斷d數組裡面元素的值,58 // 就知道a、b數組裡面每個數字出現的次數59 // 所以一定需要求出最大的哪個元素,用來確定d數組的長度60 61 int *d = new int[maxnum + 1];62 memset(d, 0, sizeof(int)*(maxnum + 1)); //將d數組全部初始化為063 64 cout << "組合後的數組是:";65 printarray(c, counta + countb);66 67 cout << "相同的數字:";68 for (i = 0, j = 0; i < counta + countb; i++)69 {70 if (d[c[i]] >= 1)//如果d[c[i]]的值大於等於1,那麼說明這個下標的值在組合數組c裡面已經出現過1次以上71 {72 d[c[i]]++;73 cout << c[i] <<" ";74 }75 else76 {77 d[c[i]]++;78 }79 }80 81 cout << "\na數組和b數組不相同的數字是:";82 for (i = 0; i <= maxnum; i++)83 {84 if (d[i] == 1)85 {86 cout << i << " ";87 }88 }89 cout << endl;90 91 return 0;92 }
運行結果: