我正在尝试找到一种方法来找到 4 个元素的数组中最大的两个数字,我现在使用的方法是这样的:
开始于
x = array[1]
y = array[2]
compare x,y
if y > x then switch the values "because i want x to have the greatest value"
read array[3] if it greater than x then make it the new x and give x value to y
else if check if it greater than y if yes then make it the new y
但是对比太多了,想减少。你们有更好的算法吗?
最佳答案
是的,实际上您会对每个指标进行大量比较。 为什么根本找不到最大值,将其从数组中删除然后找到最大值?
你的算法将是 O(2n) 所以 O(n)
关于arrays - 4 元素数组中的两个最大数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26805449/