寻找水王(2)
求解內容極其相似,相同的思路進行求解即可。同時刪除4個不同的ID后,剩余數據中3個多數id仍然是多數ID。
上題只需要一個結果,而現在需要3個結果,上題用到的nTimes,也應改為3個計數器。現在我們需要3個變量來記錄當前遍歷過的3個不同的ID,而nTimes的3個元素分別對應當前遍歷過的3個ID出現的個數。如果遍歷中有某個ID不同于這3個當前ID,我們就判斷當前3個ID是否有某個的nTimes為0,如果有,那這個新遍歷的ID就取而代之,并賦1為它的遍歷數(即nTimes減1),如果當前3個ID的nTimes皆不為0,則3個ID的nTimes皆減去1。
1 #include <iostream> 2 3 using namespace std; 4 5 int candidate[3]; 6 int count[3] = {0}; 7 8 int input[100]; 9 int num = 0; 10 11 int main() 12 { 13 cout<<"please input"<<endl; 14 int t; 15 while(cin>>t) 16 { 17 if (t == -1) 18 break; 19 input[num++] = t; 20 } 21 22 bool flag = false; 23 24 for (int i = 0;i < num;i++) 25 { 26 flag = false; 27 for (int j = 0;j < 3;j++) 28 { 29 if (count[j] == 0) 30 { 31 continue; 32 } 33 if (candidate[j] == input[i]) 34 { 35 count[j]++; 36 flag = true; 37 } 38 } 39 40 if (flag == true) 41 { 42 continue; 43 } 44 45 for (int j = 0;j < 3;j++) 46 { 47 if (count[j] == 0) 48 { 49 candidate[j] = input[i]; 50 count[j]++; 51 flag = true; 52 break; 53 } 54 } 55 56 if (flag == true) 57 { 58 continue; 59 } 60 61 for (int j = 0;j < 3;j++) 62 { 63 count[j]--; 64 } 65 66 } 67 68 cout<<count[0]<<" "<<count[1]<<" "<<count[2]<<endl; 69 cout<<candidate[0]<<" "<<candidate[1]<<" "<<candidate[2]<<endl; 70 }?
轉載于:https://www.cnblogs.com/ly199553/p/5607949.html
總結
- 上一篇: 使用系统的CoreLocation定位
- 下一篇: XCopy命令实现增量备份