[英]Why am i getting a “Your code did not execute within the time limits” on hacker rank?
[英]Why does my code return 2 when I think it should return 1? (Part of a Hacker Rank problem)
我認為輸出應該為1,但我仍會得到2。黑客排名問題稱為“遷移鳥”。 從本質上講,我得到了一個數字數組,所有數字都必須是1到5的整數。我要做的就是確定哪個數字在數組中顯示最多。 如果存在平局,則返回出現最多的最小整數。 好吧,直到他們成為平手,我的解決方案才有效。 由於某種原因,也許是基本的,而我只是想念它。 我的代碼在我認為不應該更新時也更新了1。 我正在根據自己的輸入進行測試:1 2 3 4 5 1 2 3 4 5.無論如何,如果有人想幫助我,將不勝感激。
static int migratoryBirds(List<Integer> arr) {
Map <Integer, Integer> map = new HashMap<Integer, Integer>();
int max = -1;
for(int i = 0; i < arr.size(); i++){
if(map.containsKey(arr.get(i))){
map.put(arr.get(i), map.get(arr.get(i)) + 1);
}else{
map.put(arr.get(i), 1);
}
}
for (Map.Entry<Integer,Integer> entry : map.entrySet()){
if(entry.getValue() > max){
max = entry.getKey();
System.out.println(max);
}
}
return max;
}
當我認為我的代碼應該給出1時,輸入1 2 3 4 5 1 2 3 4 5給出2。
您的max
變量中可能存在此問題。 你比較映射值max
,然后如果該值大於max
您存放在該值的關鍵max
。 在下一次迭代中,您將比較一個值和存儲在max
的鍵,這可能不正確。
提示:嘗試維護兩個變量maxKey
和maxValue
。 看到它起作用后,請清除冗余代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.