题解 | #奶牛排队问题#
奶牛排队问题
https://www.nowcoder.com/practice/e974a33a14a344278c3a359a1ebf833e
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param weights int整型vector
* @param n int整型
* @param k int整型
* @return bool布尔型
*/
bool checkDuplicate(vector<int>& weights, int n, int k) {
// write code here
// 哈希表
unordered_map<int,int> um;
for(int i=0; i<n; ++i)
{
if(um.count(weights[i]))
{
// 两头奶牛的体重相同且它们在队列中的距离不超过 k
if(i-um[weights[i]]<=k)
return true;
// 否则更新um[weights[i]]
um[weights[i]] = i;
}
else
um[weights[i]] = i;
}
return false;
}
};
查看14道真题和解析
