關於求出兩個整形數組不同元素,要求效率最高

來源:互聯網
上載者:User

標籤: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 }

 運行結果:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.