查找范围中的最大和第二大元素 [英] Find largest and second largest element in a range

查看:149
本文介绍了查找范围中的最大和第二大元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不删除最大元素并重新搜索的情况下查找上述内容?有没有更有效的方法来做到这一点?

How do I find the above without removing the largest element and searching again? Is there a more efficient way to do this? It does not matter if the these elements are duplicates.

推荐答案

for (e: all elements) {
 if (e > largest) {
   second = largest;
   largest = e;
 } else if (e > second) {
   second = e;
 }
}

您可以初始化 第二到适当的下限,或列表中的前两个项目(检查哪个更大,检查列表是否至少有两个项目)

You could either initialize largest and second to an appropriate lower bound, or to the first two items in the list (check which one is bigger, and don't forget to check if the list has at least two items)

这篇关于查找范围中的最大和第二大元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆