题解 | #草原上优势牛种#
草原上优势牛种
https://www.nowcoder.com/practice/178705f48adc4e39ac8537a22e8941cd
考察的知识点:数组;
解答方法分析:
- 首先,定义一个unordered_map<int, int> count,用于记录每个牛种的数量。
- 遍历数组nums,将每个牛种作为键,数量作为值存入哈希表count中。
- 在遍历过程中,判断当前牛种的数量是否超过了数组总数量的一半(n / 2)。如果超过了,说明找到了优势牛种,直接返回该牛种。如果没有找到优势牛种,继续遍历数组,直到找到为止。
- 如果遍历完数组仍然没有找到优势牛种,说明不存在满足条件的牛种,返回-1。
所用编程语言:C++;
完整编程代码:↓
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型vector * @return int整型 */ int majority_cow(vector<int>& nums) { unordered_map<int, int> count; int n = nums.size(); for (int i = 0; i < n; i++) { count[nums[i]]++; if (count[nums[i]] > n / 2) { return nums[i]; } } return -1; } };