英文:
Why does for each loop in java does not access the last element?
问题
我正在尝试迭代整数哈希集,以找到前两个最大的元素。我的第二个最大元素位于哈希集的末尾,我刚刚发现foreach循环跳过了最后一个元素。为什么会发生这种情况?
for (int n : set) {
if (n > max1)
max1 = n;
else if (n == max1)
max2 = n;
else if (n > max2)
max2 = n;
}
英文:
I am trying to iterate over an Integer hashset to find the first two greatest elements. My 2nd greatest element is at the end of the hashset and I just discovered that the foreach loop is skipping the last element. Why is this happening?
for(int n:set)
{
if(n>max1)
max1=n;
else if(n==max1)
max2=n;
else if(n>max2)
max2=n;
}
答案1
得分: 1
问题不在于循环,而在于您在每次迭代中没有正确更新 max1
和 max2
:
for(int n : set) {
if (n > max1) {
max2 = max1;
max1 = n;
} else if (n > max2) {
max2 = n;
}
}
请注意,由于这是一个集合,且值是唯一的,所以不应出现 n
等于 max1
或 max2
的情况。
英文:
The issue isn't the loop, but the fact you aren't properly updating both max1
and max2
in each iteration:
for(int n : set) {
if (n > max1) {
max2 = max1;
max1 = n;
} else if (n > max2) {
max2 = n;
}
}
Note that since it's a set, and the values are unique, there should be no case when n
is equal to max1
or max2
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论