【问题标题】:Return the two largest integers in an array of values返回值数组中的两个最大整数
【发布时间】:2018-08-24 02:54:07
【问题描述】:

我试图从我的 int 数组中返回两个最大的整数。 我能够返回最大和最小的罚款,但我无法让我的算法返回最大的两个。 非常感谢您提供任何帮助。

请原谅我的代码中的任何错误。这是一个练习课,题目取自去年大学的考试材料。

这是我的代码:

public class TwoLargestIntsArray {

public static void main(String [] args){

    int [] values = new int[5];

    values[0] = 5;
    values[1] = 10;
    values[2] = 15;
    values[3] = 20;
    values[4] = 25;

    System.out.println(twoLargest(values));
    System.out.println();

}

public static int twoLargest(int values[]){

    int largestA = values[0];
    int largestB = values[0];

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

            if(values[i] > largestA){
                largestA = values[i];
            }
            if(values[i] < largestA){
                largestB = values[i];   
            }

    }
    return largestA + largestB; 
}

}

【问题讨论】:

  • 数组是一维数组还是n维数组?
  • 我已经给出了答案:)

标签: java arrays


【解决方案1】:

你可以写

public static int[] twoLargest(int values[]){
    int largestA = Integer.MIN_VALUE, largestB = Integer.MIN_VALUE;

    for(int value : values) {
        if(value > largestA) {
            largestB = largestA;
            largestA = value;
        } else if (value > largestB) {
            largestB = value;
        }
    }
    return new int[] { largestA, largestB }; 
}

【讨论】:

  • 谢谢彼得。我现在就试试。 =]
  • 嘿彼得,它抛出了一个异常:线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 30 at TwoLargestIntsArray.twoLargest(TwoLargestIntsArray.java:22) at TwoLargestIntsArray.main(TwoLargestIntsArray.java: 13)
  • 我修改了 for 循环,因为我认为是这样。但是输出是这样的 - [I@56e5b723 有什么想法吗?
  • 我也修复了循环。您需要Arrays.toString(array) 才能获得数组的合理输出。
  • 好吧,在我的机器上它产生:[2, -2147483648]
【解决方案2】:
public static void twoLargest(int values[]){

    int largestA = values[0];
    int largestB = -1;

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

            if(values[i] > largestA){
                largestB = largestA;
                largestA = values[i];
            }
            else if (values[i] > largestB && values[i] != largestA) {
                largestB = values[i];
            }
    }
    System.out.println("Largest - " + largestA);
    System.out.println("2nd largest Largest - " + largestB);
}

【讨论】:

  • 是的,我改变了我的数组和值 [0] = 30。这使得最大 B = 0。
  • 你为什么让最大B = -1 只是出于兴趣?
  • Introduction To Algorithms 表示在最坏的情况下可以通过n + ceil(lg n) - 2 比较找到n 个元素中第二小的(当然是第二大的)。如何处理?
  • 真的吗?好的,我会看看的。谢谢你的帮助。尽管这似乎是一个小问题,但反应却是多种多样的。很有趣。
  • @Joachim Isaksson 你会如何解决这个问题?
【解决方案3】:
public class Test
{

public static int[] findTwoHighestDistinctValues(int[] array)
{
    int max = Integer.MIN_VALUE;
    int secondMax = Integer.MIN_VALUE;
    for (int value:array)
    {
        if (value > max)
        {
            secondMax = max;
            max = value;
        }
        else if (value > secondMax && value < max)
        {
            secondMax = value;
        }
    }
    return new int[] { max, secondMax };
}

public static void main(String []args)
{
    int [] values = new int[5];
        values[0] = 5;
        values[1] = 10;
        values[2] = 15;
        values[3] = 20;
        values[4] = 25;
    int []ar = findTwoHighestDistinctValues(values);
    System.out.println("1 = "+ar[0]);
    System.out.println("2 = "+ar[1]);
}  
}

输出:

1 = 25

2 = 20

【讨论】:

  • 如果有任何重复项,我会比较(值 >= 最大值)
【解决方案4】:

您不能让单个函数返回 2 个值。您要么必须将它们包装在一个数组中,要么使用引用参数。

【讨论】:

    【解决方案5】:

    传递要填充值的数组:

    public static void twoLargest(int [] values, int [] ret){
        //...
        ret[0] = largestA;
        ret[1] = largestB;
    }
    
    
    int [] ret = new int [2];
    twoLargest(values, ret);
    // now ret[0] is largestA
    // and ret[1] is largestB
    

    【讨论】:

      【解决方案6】:

      试试这个:

      public static int[] twoLargest(int values[]){
      
          int[] result = new int[2];
          int largestA = 0;
          int largestB = 0;
      
          for(int i = 0; i < values.length; i++){
      
                  if(values[i] > largestA){
                  largestB = largestA;
                  largestA = values[i];
              }
          }
           result[0] = largestA;
           result[1] = largestB;
      
          return result; 
      }
      

      【讨论】:

      • 最大值可能为负数。
      【解决方案7】:

      如果您能够从函数中获得最大、第二大、第三大等等,我假设它会对您有所帮助。我创造了这样一个:

      public static int xLargest(int values[], int largeIndex)
      

      只需传递数组和 largeIndex,最大的发送 1,第二大的发送 2,依此类推。

      import java.util.ArrayList;
      import java.util.Collections;
      import java.util.List;
      
      public class XLargestIntArray {
      
          public static void main(String[] args) {
      
              int[] values = new int[5];
      
              values[0] = 5;
              values[1] = 10;
              values[2] = 15;
              values[3] = 20;
              values[4] = 25;
      
              System.out.println(xLargest(values,2));
              System.out.println();
      
          }
      
          public static int xLargest(int values[], int largeIndex) {
      
              List<Integer> intList = new ArrayList<Integer>();
              for (int index = 0; index < values.length; index++) {
                  intList.add(values[index]);
              }
              Collections.sort(intList);
              return intList.get(intList.size() - largeIndex);
          }
      }
      

      【讨论】:

      • 您可以对数组进行排序。您不必创建整数列表,只需对其进行排序即可。
      【解决方案8】:

      您还可以使用嵌套类来存储计算结果。例如:

        private static class Result {
      
          int largestA;
          int largestB;
      
          Result(int largestA, int largestB) {
              this.largestA = largestA;
              this.largestB = largestB;
          }
      }
      

      然后接收类似这样的数据:

      Result result = twoLargest(values);
      System.out.println(result.largestA);
      System.out.println(result.largestB);
      

      【讨论】:

        【解决方案9】:

        @Nilesh Jadav 的回答涵盖了所有情况。如果数组的最大值是最后一个元素,@Peter Lawrey 的回答会失败。例如 [10,2,5,1,8,20] 返回 20 和 8 以及接受的解决方案。

        【讨论】:

          【解决方案10】:
           public static void main(String[] args) {
          
              int[] numbers = new int[]{1, 2, 5, 4, 57, 54, 656, 4};
              int temp = numbers[0];
              int max = temp;
              int lastMax = temp;
          
              for (int index = 1; index < numbers.length; index++){
                  int currentIndex = numbers[index];
          
                  // check any time is it bigger than current maximum value
                  max = Math.max(max, currentIndex);
          
                  // if is grow up then should be max != temp; set old Max in last or 
                  // is not group up but current index is bigger then last index update last max value
                  lastMax = max != temp ? temp : Math.max(currentIndex, lastMax);
          
                  temp = max;
              }
          
              System.out.println("Last max: " + lastMax);
              System.out.println("Max:" + max);
          }
          

          【讨论】:

            【解决方案11】:
            private static void printTwoMaxNumberWithoutSortMethod(int[] input) {
                int max=0,lastMax=0;
                lastMax=input[0];
                max=input[0];
                for(int i=1;i<input.length;i++)
                {
                    if(lastMax<input[i] & max<input[i])
                    {
                        lastMax=max;
                        max=input[i];
            
                    }
                }
                System.out.println("lastMax="+lastMax+" : max="+max);
            
            }
            

            【讨论】:

            • 请问您能用代码或文字记录您的代码吗?
            • 虽然此代码 sn-p 可能是解决方案,但 including an explanation 确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
            【解决方案12】:
               //Java8&9 makes this easier with a cleaner code
               int[] numbers = new int[]{1, 2, 5, 4, 57, 54, 656, 4};       
                int maxSize = 2;
                Arrays.stream(numbers) //stream
                .boxed()  //to Integer Object
                .sorted(Comparator.reverseOrder()) //sorted
                .limit(maxSize )  //keep N values
                .forEach(System.out::println); 
            

            注意。我们可以将此 astuce 与任何实现可比较的 bean 对象或通过使用相关的自定义比较器一起使用。

            【讨论】:

              【解决方案13】:
              public class TwoLargestIntArray {
              
              
                  public static void main(String [] args){
              
                      int a[]  = new int[5];
              
                      a[0] = 110;
                      a[1] = 50;
                      a[2] = 15;
                      a[3] = 30;
                      a[4] = 60;
              
                      System.out.println(twoLargest(a));
                      System.out.println();
              
                  }
              
                  public static int twoLargest(int a[]){
              
                      int firstMax = 0;
                      int secondMax = 0;
              
                      for(int i = 0; i < a.length; i++){
              
                              if(a[i]>firstMax) {
                                  secondMax=firstMax;
                                  firstMax = a[i];}
                                  else if (a[i]>secondMax) {
                                      secondMax= a[i];
                                  }
              
                                  }
              
              
              
              
                      return  firstMax + secondMax; 
                  }}
              

              【讨论】:

              • 那个 preview 窗口的存在是有原因的:因此您可以在提交之前检查您的输入。请花一些时间并正确缩进/格式化所有代码。转储超级难读的代码是没有意义的,只是因为你没有花 10 秒来删除空行或以合理的方式缩进!
              【解决方案14】:

              如果这里的性能不是问题,它不应该出现在小型数组上,这可以用更少的代码来完成。

              最直接的解决方案是简单地对数组进行排序并返回它的最后一个值,并且在最后一个值的旁边:

              public static int[] twoLargest(int[] values) {
                  Arrays.sort(values);
                  return new int[]{values[values.length - 1], values[values.length - 2]};
              }
              

              上述代码的时间复杂度为O(n log (n)),如Arrays.sort()的Javadoc中所述:

              实施说明:排序算法是 Vladimir Yaroslavskiy、Jon Bentley 和 Joshua Bloch 的 Dual-Pivot Quicksort。该算法在许多数据集上提供 O(n log(n)) 性能,导致其他快速排序降低到二次性能,并且通常比传统(单轴)快速排序实现更快。

              如果预期输入是一个少于两个元素的数组,则需要添加一些错误处理,例如抛出异常。

              【讨论】:

                【解决方案15】:
                public static int Compute(int _arrValues[]){
                
                        int _intX = _arrValues[0];
                        int _intY = _arrValues[1];
                
                        for(int i = 2; i < _arrValues.length; i++){
                
                                if(_arrValues[i] > _intX){
                                    _intX= values[i];
                                }
                                else if(_arrValues[i] > _intY){
                                    _intY = values[i];   
                                }
                        }
                        return _intX + _intY; 
                    }
                

                【讨论】:

                • 请使用edit链接来解释这段代码是如何工作的,不要只给出代码,因为解释更有可能帮助未来的读者。另见How to Answer。 source
                【解决方案16】:

                试试这个

                int [] array1={10,2,5,1,8,20};
                
                int largest= array1[0];
                
                int seclargest=array1[0];
                
                for (int i=1;i<array1.length;i++)
                {
                    if(largest <= array1[i])
                    {
                        seclargest=largest;
                        largest=array1[i];  
                    }   
                
                }
                
                System.out.println("largest and second largest are:" +largest + " " +seclargest);
                

                【讨论】:

                • 以下输入失败:array1 = {6, 9, 3, 1, 7}
                猜你喜欢
                • 1970-01-01
                • 2016-05-16
                • 1970-01-01
                • 2021-06-09
                • 2014-11-27
                • 2017-06-24
                • 2019-03-26
                • 2012-07-03
                • 2017-11-06
                相关资源
                最近更新 更多