题解 | #乳牛研究成果评估#
乳牛研究成果评估
https://www.nowcoder.com/practice/00e2e90dd8a24e1695cee8c3cb339390
知识点
哈希,贪心
思路
使用map建立奶牛指数到出现次数的映射,对于milk[i],从1milk[i]指数它都涵盖出现了一次,mp[1milk[i]]的值都++。
遍历一次milk数组,预处理所有的指数以及出现的次数。
初始化ans为-1(小值)
然后再遍历map,若map.second>=map.first(即出现次数n不小于n公斤),且map.first>ans(多个牛奶指数取n大的),则更新答案。ans即为所求。
代码c++
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param milk_production int整型vector
* @return int整型
*/
int cow_hp(vector<int>& milk_production) {
// write code here
map<int,int>mp;
for(auto v:milk_production)
{
for(int i=1;i<=v;i++)mp[i]++;
}
int ans=-1;
for(auto v:mp)
{
if(v.second>=v.first&&v.first>ans)
{
ans=v.first;
}
}
return ans;
}
};