本文介绍了如何找到最大值和分钟.在数组中使用最小比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一道面试题:给定一个整数数组,找出最大值.和分钟.使用最少的比较.

This is a interview question: given an array of integers find the max. and min. using minimum comparisons.

显然,我可以在数组上循环两次并在最坏的情况下使用 ~2n 比较,但我想做得更好.

Obviously, I can loop over the array twice and use ~2n comparisons in the worst case but I would like to do better.

推荐答案

1. Pick 2 elements(a, b), compare them. (say a > b)
2. Update min by comparing (min, b)
3. Update max by comparing (max, a)

通过这种方式,您将对 2 个元素进行 3 次比较,总计 3N/2 次对 N 元素的总比较.

This way you would do 3 comparisons for 2 elements, amounting to 3N/2 total comparisons for N elements.

这篇关于如何找到最大值和分钟.在数组中使用最小比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 23:25