简体   繁体   English

打印数组中的2个最高数字

[英]Printing the 2 highest numbers in an Array

So I created a method called max2 that is supposed to return the 2 highest values in an array. 因此,我创建了一个名为max2的方法,该方法应该返回数组中的2个最大值。 I am able to return the highest value however I cannot figure out how to return the second highest value. 我能够返回最高值,但是我不知道如何返回第二高值。

Here is my code: Main Method 这是我的代码:主要方法

    public static void main(String[] args) {
        Integer intArray[] = { 13, 25, 46, 65, 12, 23};
        Double doubleArray[] = {1.2, 3.4, 1.1, 0.1, 5.6};
        String stringArray[] = {"H", "E", "L", "L", "O"};

    System.out.println("The smallest number is: " + myMin(doubleArray));
    System.out.println("The median is: " + median(doubleArray));
    System.out.println("The median is: " + median(stringArray));
    System.out.println("The max is: " + max2(intArray));
}

My max2 method: 我的max2方法:

public static <E extends Comparable<E>> E max2(E... elements) {

Arrays.sort(elements);

    E max = elements[0];
    for (E element : elements) {
        if (element.compareTo(max) > 0) {
            max = element;

        }
    }
    return max;

}

I am wondering if there is a way to get the 2nd to last index of the array. 我想知道是否有一种方法来获取数组的倒数第二个索引。 Ideally I would want this to work with any array. 理想情况下,我希望它可以与任何数组一起使用。 I am looking to be pointed into the right direction. 我希望被指出正确的方向。 Thank you for your help. 谢谢您的帮助。

You can use Java 8 streams to remove duplicates and sort the array, and use length-1 and length-2 to get max and second max element from array 您可以使用Java 8流删除重复项并对数组进行排序,并使用length-1length-2从数组中获取max和second max元素

Integer intArray[] = { 13,13, 25, 46,25, 65, 12, 23};
    Double doubleArray[] = {1.2, 3.4, 1.1, 0.1, 5.6};
    String stringArray[] = {"H", "E", "L", "L", "O"};

   Integer[] s= Arrays.stream(intArray).sorted().distinct().toArray(Integer[]::new);
   System.out.println(Arrays.toString(s));
   int max = s[s.length-1];
   int max2 = s[s.length-2];

or if you just want to sort array then you should use Arrays.sort to sort array and get the max and second max element 或者,如果您只想对数组进行排序,则应使用Arrays.sort对数组进行排序并获取max和second max元素

Arrays.sort(intArray) 
int max = s[s.length-1];
int max2 = s[s.length-2];

we need to sort an array on descending order you can use bubble sort, now we can get the last index value as highest number and second last index as second highest number. 我们需要按降序对数组进行排序,您可以使用冒泡排序,现在我们可以将最后一个索引值作为最高数字,将倒数第二个索引作为第二高数字。 example. 例。

class ReturnTwoHeighestNumber {
  public static void main(String...args) {
   int arr[] = {12,13,15,6,9,30,50,19};
   ReturnTwoHeighestNumber number = new ReturnTwoHeighestNumber();
   number.bubleSort(arr);
   number.printTwohighestNumber(arr)   
  }
  void bubleSort(int arr[]) {
  int n= arr.length;
   for(int i=0; j<n-1;i++) {
      for(int j=0;j<n-i-1; j++) {
         if(arr[j]> arr[j+1]) {
          int temp = arr[1];
          arr[j] = arr[j+1];
          arr[j+1] = temp;
         }
      }
   }
  void printTwohighestNumber(int arr[]) {
    int n= arr.length;
    for(int j=0;j<n;++j) {
      System.out.print(arr[j]+" ");
      System.out.println();  
    }
     System.out.println("My first highest Number is "+ arr[arr.length-1]);
     System.out.println("My Second highest Number is "+arr[arr.length-2]);   
  }    

  } 
}

Your approach 你的方法

Your current approach doesn't make much sense. 您当前的方法没有多大意义。 You have 你有

Arrays.sort(elements);

E max = elements[0];
for (E element : elements) {
    if (element.compareTo(max) > 0) {
        max = element;
    }
}
return max;

That is, you first sort the array. 也就是说,您首先对数组进行排序。 And then you traverse all elements to find the max -element. 然后遍历所有元素以找到max -element。 First, you wanted to find the second to max element, not the max element. 首先,您想找到第二个元素而不是max元素。 And second, why are you sorting when you then don't exploit the fact that it is sorted, but just iterate through the array? 其次,为什么在不利用已排序的事实而只是遍历数组的情况下进行排序呢?

Let me show you some solutions. 让我向您展示一些解决方案。


Full sort 全分类

Probably the easiest solution is to do a full sort and then access the second to last element (elements are sorted ascending by default): 可能最简单的解决方案是进行完整排序 ,然后访问倒数第二个元素(默认情况下,元素按升序排序):

Arrays.sort(values);
return values[values.length - 2];

There is one problem with this approach. 这种方法存在一个问题。 Arrays.sort sorts the given array inline. Arrays.sort对给定的数组进行内联排序。 That is, it changes your input array. 也就是说,它会更改您的输入数组。 You probably do not want this and only want to sort a copy. 您可能不希望这样,而只想对副本进行排序。 So: 所以:

E[] copyValues = values.clone();
Arrays.sort(copyValues);
return copyValues[copyValues.length - 2];

Partial sort 部分排序

Instead of doing a full sort, you can always do a partial sort (k-sort). 除了完全排序之外,您始终可以执行部分​​排序(k排序)。 This will be faster, as you only need to sort the array descending for 2 elements. 这样会更快,因为您只需要对2个元素降序排列。 You can do a partial sort using a PriorityQueue . 您可以使用PriorityQueue进行部分排序。 Insert all elements into the queue and then call poll two times. 将所有元素插入队列,然后调用poll两次。 The queue always gives you the next element according to the order. 队列总是根据顺序为您提供下一个元素。

PriorityQueue<E> queue = new PriorityQueue<>(Comparator.reverseOrder());
queue.addAll(Arrays.asList(values);

queue.poll(); // Greatest element
return queue.poll(); // Second to greatest element

Iteration 迭代

Probably the fastest solution is to do one ordinary iteration and remembering the greatest, as well as the second to greatest element. 最快的解决方案可能是进行一次普通的迭代并记住最大的迭代,以及第二至最大的迭代。 This is similar to the loop in your approach, but including remembering the second to greatest element. 这与您的方法中的循环类似,但包括记住倒数第二个要素。

E max = values[0];
E secondMax = values[0];

for (E element : elements) {
    if (element.compareTo(max) > 0) {
        secondMax = max;
        max = element;
    } else if (element.compareTo(secondMax) > 0) {
        secondMax = element;
    }
}

return secondMax;

Note that you need to remember the max element too, since you want to find an element that is not greater than max , but still greater than the rest. 请注意,您还需要记住max元素,因为您想要找到一个不大于max ,但仍然大于其余元素的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM