如何解决Java:抢第二高[重复项]
| 这个问题已经在这里有了答案:解决方法
O(n)速度这样的事情怎么样:
// first,second,d0,d1,di all typed by whatever getValue() returns...
// This assumes you have at least two elements in your Dices array
d0 = Dices[0].getValue();
d1 = Dices[1].getValue();
if (d0 > d1) {
first=d0;
second=d1;
} else {
first=d1;
second=d0;
}
for (int i = 2; i < Dices.length; i++) {
di = Dices[i].getValue();
if (di > first) {
second = first;
first = di;
} else if (di > second)
second = di;
}
,使用自定义对数组排序
Comparator
(复制数组
如果您无法对原件进行排序)
选择排序数组的最后一项:
// hopefully you have checked in advance that there is more than one item
return sortedDices[sortedDices.length-2];
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。