gpt4 book ai didi

java - 如何在不使用数组且仅使用三个比较器或比较的情况下从 4 个输入中找到第三大数字

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:12:44 24 4
gpt4 key购买 nike

我写的代码如下:

 /*
Program to find the 3rd largest no from 4 nos without using arrays and
only using 3 comparators or comparisons

*/
package d;


public class thirdlargest {
public static void main(String args[]) {

int a=1,b=2,c=3,d=4,soln;
soln= Math.min(Math.max(a,b),Math.max(c,d));
System.out.println("Third largest=" +soln);
}
}
/*
Output:
Third largest=2
*/

但这只适用于输入的使用模式,如果我改变模式输出将是错误的。如何仅使用 3 个比较器或严格比较来修复此代码,我们可以使用任何编程语言

最佳答案

IMO 不可能仅使用三次比较就从 4 个数字中找到第三大数字:

 public static void main(String[] args) throws IOException {
int a=1,b=2,c=3,d=4,soln;
int maximum1 = Math.max(a,b);
int maximum2 = Math.max(c,d);

if(maximum1 < maximum2) {
// either c or d and we need more comparisons
}
else {
// either a or b and we need more comparisons
}
}

编辑:实际上我们可以使用 3 次比较找到最大或最小的数字,但可能不是第三大等。

同时检查这个 answerO(n) 时间内找到第 k 个最大的数。

关于java - 如何在不使用数组且仅使用三个比较器或比较的情况下从 4 个输入中找到第三大数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32804262/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com