简体   繁体   English

数组元素,排列和标识元素

[英]array elements, arranging and identifying elements

How can I find the 2nd largest element in the array, Here is my code but I can't figure out the problem, help would be much appreciated 我如何找到数组中第二大的元素,这是我的代码,但我无法弄清楚问题,将不胜感激

import java.util.Arrays;
import java.util.Random;

public class NDlargest
{
    Random random = new Random();
    private int[] array = new int[10];
    private int largest;
    private int largest2;

    public NDlargest()
    {
        largest = 0;
        largest2 = 0;

        for (int i =0; i< array.length; i++)
        {
            array[i] = 1 + random.nextInt(100);
        }
         System.out.println(Arrays.toString(array));
    }

    public int getLargest()
    {

    for (int i = 0; i < array.length; i++)
    {
        int number = array[i];

        if (number > largest)
        { 
            largest = number;
        }
    }
    return largest;
}


   public int getSecondLargest()
   {
       for (int i = 0; i < array.length; i++)
       {
           int number2 = array[i];
           if  (largest2 < largest)
           {
               if (number2 > largest2)
               {
                   largest2 = number2;
                } 
            }
            else
           {

              break;
            }
        }
             return largest2;


}}
       int number2 = array[i];
       // here is the problem
       if  (largest2 < largest) 

Please replace with the following. 请替换以下内容。

        int number2 = array[i];
        if  (number2 < largest)

Little optimized version of your methods. 方法的最佳化版本。

    public int getLargest()
    {

       for (int i = 0; i < array.length; i++)
       {       

           if (array[i] > largest)
           { 
              largest = array[i];
           }
       }
       return largest;
    }


    public int getSecondLargest()
    {
       for (int i = 0; i < array.length; i++)
       {          
           if  (array[i] < largest)
           {
               if (array[i] > largest2)
               {
                   largest2 = array[i];
                } 
            }

        }
        return largest2;   
    }

Change your getSecondLargest() code like: 更改您的getSecondLargest()代码,例如:

public int getSecondLargest() {
        Arrays.sort(array);
        largest2=array[array.length-2];
        return largest2;

}

Start with asking why is break required in your code of finding the second largest number? 首先要问为什么查找第二大数字的代码中需要中断? Essentially, can you find second largest number without looking at all numbers in a list ? 本质上,您是否可以查找第二大数字而不查看列表中的所有数字?

Then, to understand a general solution for finding kth element in a list without sorting, look at http://pine.cs.yale.edu/pinewiki/QuickSelect . 然后,要了解用于在列表中查找第k个元素而不进行排序的一般解决方案,请查看http://pine.cs.yale.edu/pinewiki/QuickSelect

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

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