Fastest way of finding the middle value of a triple?(找到三元组中间值的最快方法?)
问题描述
Given 是一个由三个数值组成的数组,我想知道这三个数值的中间值.
Given is an array of three numeric values and I'd like to know the middle value of the three.
问题是,找到三个中间的最快方法是什么?
The question is, what is the fastest way of finding the middle of the three?
我的方法是这种模式 - 因为有三个数字,所以有六个排列:
My approach is this kind of pattern - as there are three numbers there are six permutations:
if (array[randomIndexA] >= array[randomIndexB] &&
array[randomIndexB] >= array[randomIndexC])
如果有人能帮助我找到一种更优雅和更快的方法,那就太好了.
It would be really nice, if someone could help me out finding a more elegant and faster way of doing this.
推荐答案
如果你正在寻找最有效的解决方案,我想它是这样的:
If you are looking for the most efficient solution, I would imagine that it is something like this:
if (array[randomIndexA] > array[randomIndexB]) {
if (array[randomIndexB] > array[randomIndexC]) {
return "b is the middle value";
} else if (array[randomIndexA] > array[randomIndexC]) {
return "c is the middle value";
} else {
return "a is the middle value";
}
} else {
if (array[randomIndexA] > array[randomIndexC]) {
return "a is the middle value";
} else if (array[randomIndexB] > array[randomIndexC]) {
return "c is the middle value";
} else {
return "b is the middle value";
}
}
这种方法需要至少两次,最多三个比较.它故意忽略了两个值相等的可能性(就像您的问题一样):如果这很重要,则可以扩展该方法以检查这一点.
This approach requires at least two and at most three comparisons. It deliberately ignores the possibility of two values being equal (as did your question): if this is important, the approach can be extended to check this also.
这篇关于找到三元组中间值的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:找到三元组中间值的最快方法?
基础教程推荐
- Java:带有char数组的println给出乱码 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 降序排序:Java Map 2022-01-01