数组中的第三大数字? [英] The third largest number in an array?

查看:81
本文介绍了数组中的第三大数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能告诉我如何在数组中找到第三大数字吗?

无需订购

感谢您的答案

can you tell me how to find third largest number in an array?
without ordering
thanks for answers

推荐答案

就个人而言,我会订购它们:按降序排序会使它成为一个微不足道的问题。

但是如果你不允许使用排序,那就是它的功课。所以你没有得到代码!



但它并不复杂。

想一想:你怎么找到最大值? br />
答案:循环虽然数组中的所有条目都与当前值进行比较。如果这个值大于当前它就会成为新的最大值。



让这个找到前三个是一件非常简单的事情:当你更换最大值时,移动它进入第二大,第二进入第三。一次完成,完成。
Personally, I would order them: sorted into descending order would make it a trivial problem.
But if you aren't allowed to use sorting, then it's homework. So you don't get code!

But it's not complex.
Think about it: how would you find the maximum value?
Answer: Loop though all entries in the array comparing each against the current value. If this value is larger than current it becomes the new maximum.

It's a pretty simple matter to make this find the top three: when you replace the maximum, move it into the second largest, and the second into the third. One pass, done.


如果由于某种原因无法对数组进行排序,则可以始终创建一个仅反映顺序的附加索引,然后使用此索引来定位需要元素。
If you can't order the array for whatever reasons, you can always create an additional index that will just reflect the order, and then use this index to locate the needed element.


//获取三个变量并分配数组的第一个元素然后

检查最大的数量。如果找到则将第一个no转换为第二个变量,然后转换为第三个变量。

//Take three variable and assign first element of the array and then
check for the largest no. If found then shift the first no to second variable and so in third variable.
int[] arr = {1,8,4,5,12,2,5,6,7,1,90,100,56,8,34};

            int temp, f, s, t;
            f = s = t = arr[0];
            foreach (int i in arr)
            {
                if (f < i)
                {
                    temp = f;
                    f = i;
                    s = temp;
                }
                if (s < i && f > i)
                {
                    temp = i;
                    s = i;
                    t = temp;
                }
                if (t < i && s > i)
                {
                    temp = i;
                     t=i;
                }
            }
            MessageBox.Show(t.ToString());


这篇关于数组中的第三大数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆