题解 | #微信红包#
微信红包
https://www.nowcoder.com/practice/fbcf95ed620f42a88be24eb2cd57ec54
int getValue(vector<int> gifts, int n) { map<int, int> val_count_map; for (const auto &e : gifts) { val_count_map[e]++; } for (const auto &e : val_count_map) { if (e.second>n / 2) return e.first; } return 0; }
#include <type_traits> class Gift { public: int getValue(vector<int> gifts, int n) { sort(gifts.begin(),gifts.end()); int mid_val=gifts[n/2]; int count=0; for(const auto &e:gifts) { if(mid_val==e) count++; } if(count>n/2) return mid_val; return 0; } };
int getValue(vector<int> gifts, int n) { int flag = 1; int res = gifts[0]; int count = 0; if (n == 1) return res; for (int i = 1; i < n; i++) { if (flag == 0) { res = gifts[i]; flag = 1; continue; } if (res == gifts[i]) ++flag; else --flag; } for (int i = 0; i < n; ++i) { if (res == gifts[i]) ++count; } if (count > n / 2) return res; else return 0; }