How to find second largest number in an array in Java?

后端 未结 10 965
野的像风
野的像风 2021-01-01 05:57

I\'m just practicing some MIT java assignments. But, I\'m not sure how to find the second largest number. http://ocw.csail.mit.edu/f/13

  public class Marath         


        
10条回答
  •  难免孤独
    2021-01-01 06:20

    Instead of resorting to sorting the array, you can simply do the following:

    • Keep a largestValue and a secondLargestValue
    • Loop through the entire array once, for each element:
      • Check to see if the current element is greater than largestValue:
        • If so, assign largestValue to secondLargestValue, then assign the current element to largestValue (think of it as shifting everything down by 1)
        • If not, check to see if the current element is greater than secondLargestValue
          • If so, assign the current element to secondLargestValue
          • If not, do nothing.

    O(n) run time

    O(1) space requirement

提交回复
热议问题