【PAT甲级 找到出现次数过半的数字】1054 The Dominant Color (20 分) C++
生活随笔
收集整理的這篇文章主要介紹了
【PAT甲级 找到出现次数过半的数字】1054 The Dominant Color (20 分) C++
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目
思路
- 用數(shù)組模擬維護(hù)一個(gè)棧,棧內(nèi)存儲(chǔ)的數(shù)據(jù)有兩個(gè)屬性:數(shù)字、數(shù)量。
- 讀取數(shù)字,如果數(shù)字已存在,相應(yīng)位置上的數(shù)量+1
- 如果數(shù)字不存在,新建這個(gè)數(shù)字,size++,相應(yīng)位置上的數(shù)量設(shè)置為1
題解 C++
#include<iostream> #include<string> #include<algorithm> #define NUM 480000 using namespace std; int main() {int t1, t2;cin >> t1 >> t2;int total = t1 * t2;int arr[NUM] = { 0 };int count[NUM] = { 0 };int size = 0;//模擬一個(gè)棧//存數(shù)據(jù)int temp;for (int i = 0; i < total; i++) {bool find = false;cin >> temp;for (int j = 0; j < size; j++) {//找相同if (arr[j] == temp) {//有相同find = true;count[j]++;break;}}//沒相同if (!find) {arr[size] = temp;count[size]++;size++;}}//找過半for (int i = 0; i < total; i++) {if (count[i] > total / 2) {cout << arr[i];}}system("pause"); } 超強(qiáng)干貨來襲 云風(fēng)專訪:近40年碼齡,通宵達(dá)旦的技術(shù)人生總結(jié)
以上是生活随笔為你收集整理的【PAT甲级 找到出现次数过半的数字】1054 The Dominant Color (20 分) C++的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【PAT甲级 删除字符串中的指定字符】1
- 下一篇: 【PAT甲级 一个字符数组是否被另一个包