【问题标题】:Finding 2nd largest number in array (one look at array) [duplicate]在数组中查找第二大数(一看数组)[重复]
【发布时间】:2017-01-04 22:15:49
【问题描述】:

我之前上过一堂课,我们学习了这种算法,但找不到我的代码。如何在仅 1 次扫描的数组中找到第二大数字?

我正在考虑使用节点,但如果最大的和第二大的节点从同一侧开始,那将会搞砸。一个丑陋的方法是有两个额外的临时变量并“找到”其中较小的一个。

所以有人有任何提示吗?哦,如果你有代码,那就是 java。 同时,我会尝试在 google 上搜索更多内容!

【问题讨论】:

  • 现实生活中:Arrays.sort(myArray); return myArray[myArray.length - 2];
  • 两个额外的临时变量很好......
  • 我想我现在只使用这两个变量

标签: java arrays search


【解决方案1】:

这是我获得第二高数字的方法:

//      The array containing number.
        int[] number = {1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10};

//      The int[] is copied to Integer[] array. This is done because the Arrays class cannot sort primitives (such as int). If any other primitive type, they can be converted to their respective objects.
        Integer[] numberInteger = new Integer[number.length];

//      Populate the Integer[] with data from int[].
        for(int i = 0; i<number.length; i++)
        {
            numberInteger[i] = number[i];
        }

//      Sort the Integer[] array in reverse order.
        Arrays.sort(numberInteger, Collections.<Integer>reverseOrder());

//      Print the result out.
        System.out.println("The second highest number is: "+numberInteger[1]);

//      Output is~~~~~~~ The second highest number is: 9

如果您有其他原始类型(例如 double[]),则可以将其复制到相应的对象(例如 Double[])。

附:如果使用 Java 8,可以以更简单的方式填充 Integer[] 数组。流可用于填充 Integer[]。

//      Instead of using a for loop, Streams are used.
        Integer[] numberInteger = Arrays.stream(number).boxed().toArray(Integer[]::new);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-06
    • 2019-08-05
    • 2018-03-21
    • 1970-01-01
    • 2018-09-22
    • 2017-09-22
    • 2015-08-23
    • 1970-01-01
    相关资源
    最近更新 更多