微信红包问题:找出某个出现次数超过红包总数一半的红包的金额(面试题)
生活随笔
收集整理的這篇文章主要介紹了
微信红包问题:找出某个出现次数超过红包总数一半的红包的金额(面试题)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1、問題描述
春節(jié)期間小明使用微信收到很多個(gè)紅包,非常開心。在查看領(lǐng)取紅包記錄時(shí)發(fā)現(xiàn),某個(gè)紅包金額出現(xiàn)的次數(shù)超過了紅包總數(shù)的一半。請(qǐng)幫小明找到該紅包金額。寫出具體算法思路和代碼實(shí)現(xiàn),要求算法盡可能高效。
給定一個(gè)紅包的金額數(shù)組gifts及它的大小n,請(qǐng)返回所求紅包的金額。
測(cè)試樣例: [1,2,3,2,2],5
返回:2
2、問題思路 可以使用map統(tǒng)計(jì)每個(gè)紅包出現(xiàn)的次數(shù):map<金額,次數(shù)> 用一個(gè)迭代器遍歷map:map<金額,次數(shù)>::iterator it 找出符合條件的紅包:返回 it->first
3、代碼具體實(shí)現(xiàn)
此方法不滿足時(shí)間復(fù)雜度N:O(N) #include <iostream> #include <map> #include <vector> #include <stdlib.h>using namespace std;int getValue(vector<int> gifts, int n) {if(gifts.empty() == true)return 0;map<int, int> gifts_count; for(int i = 0; i < n; i++) { gifts_count[gifts[i]]++; } map<int, int>::iterator it = gifts_count.begin();while(it != gifts_count.end()){if(it->second > n/2)return it->first;elseit++;}return 0; }void test() {int val[] = {1,2,3,2,2};vector<int> gifts(begin(val), end(val));int ret = getValue(gifts, gifts.size());if(ret != 0)cout<<"紅包:¥"<<ret<<" 出現(xiàn)次數(shù)超過一半"<<endl;elsecout<<"沒有紅包出現(xiàn)次數(shù)超過一半"<<endl; }
滿足時(shí)間復(fù)雜度:
int getValue(vector<int> gifts, int n) {int value = gifts[0];int count = 1;for(int i = 1; i < n; ++i){if(gifts[i] != value)--count;else++count;if(count == 0)value = gifts[i];}count = 0;for(int i = 0; i < n; ++i){if(gifts[i] == value)count++;}if(count < n/2)return 0;elsereturn value; }void test() {vector<int> gifts;gifts.push_back(1);gifts.push_back(2);gifts.push_back(3);gifts.push_back(2);gifts.push_back(2);cout<<getValue(gifts, 5)<<endl; }總結(jié)
以上是生活随笔為你收集整理的微信红包问题:找出某个出现次数超过红包总数一半的红包的金额(面试题)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MongoDB的安装启动
- 下一篇: Builder 混合式开发