2017年12月11日 星期一

[C_AR188-易] 陣列元素(C++)

[C_AR188-易] 陣列元素

Time Limit: 1 seconds
問題描述 :
給一個整數陣列,裏面每個元素都是正整數,陣列的長度為 n 。請輸出陣列中的元素,這個元素的出現次數超過⌈n/2⌉ (即 >⌈n/2⌉)。
例如:陣列 arr 的長度為 4 : 1 1 1 3 ,那要輸出 1 ,因為 1 出現 3 次,且 3 > ⌈n/2⌉ = ⌈4/2⌉ = 2 。
輸入說明 :
輸入為一行字串,字串中包含了一群正整數,每個正整數都用空白隔開。字串中最多包含 500 個正整數。
輸出說明 :
計算 出現次數超過  ⌈n/2⌉的元素,並輸出,請輸出後,加一個換行符號。
若沒有任何元素其出現次數超過  ⌈n/2⌉次,那輸出 n/a 。之後也請加一個換行符號。
範例 :
Sample Input:Sample Output:
1 1 1 31
1 2 3 4n/a

  1. #include <iostream>  
  2. #include <string>  
  3. #include <sstream>  
  4.   
  5. using namespace std;  
  6.   
  7. int main() {  
  8.     // [C_AR188-易] 陣列元素  
  9.     // g++(c++11)  
  10.     string input;  
  11.     int c[1000000];  
  12.     fill(c, c+1000000, 0);  
  13.     int count = 0;  
  14.     while(getline(cin, input))  
  15.     {  
  16.         //字串切割  
  17.         bool no = false;//沒結果  
  18.         stringstream ss(input);  
  19.         string token;  
  20.         while (getline(ss, token, ' '))  
  21.         {  
  22.             c[stoi(token)]++;  
  23.             count++;  
  24.         }  
  25.         for(int i = 0;i < 1000000;i++)  
  26.         {  
  27.             if(c[i] > (count/2))  
  28.             {  
  29.                 cout << i << endl;  
  30.                 no = true;  
  31.             }  
  32.         }  
  33.         if(no == false)  
  34.         {  
  35.             cout << "n/a" << endl;  
  36.         }  
  37.     }  
  38.     return 0;  
  39. }  

沒有留言:

張貼留言