Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
127 views
in Technique[技术] by (71.8m points)

java - Find the 2nd highest no from array, where array contains duplicate values

public class Second_Largest_Number_In_Array_with_Dupes {

    public static void main(String[] args) {
        int[] a = {6,8,2,4,3,1,5,7}; 
        
        int temp ;  
        for (int i = 0; i < a.length; i++){
            for (int j = i + 1; j < a.length; j++){
                if (a[i] < a[j]){
                    temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                }
            }
        }
        
        System.out.println("Second Largest element is " + a[1]);
    }
}

This only works for array with no duplicate values.

For example it does not work for this array: int[] a = {6,8,2,4,3,1,5,7,8};

question from:https://stackoverflow.com/questions/65651835/find-the-2nd-highest-no-from-array-where-array-contains-duplicate-values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Solution

  • Initialize max and second_max with the lowest possible value Integer.MIN_Value
  • Then go through your array and check for each element if it is greater then the max_value -> When yes reassign your max_value with a[i] and reassign your second_max_value with max_malue

 if (a[i] > max) {
                temp = max;
                max = a[i];
                second_max = temp;
  • Then check if your a[i] is greater then your second_max_value and not equal to your max_value . If yes reassign your second_max_value with a[i]
    a[i] > second_max && a[i] != max

  • Last but not least check if second_max is equal to the initial value
    If yes then there is no second highest Value in your Array. Example Arrays for this case {5, 5, 5}, {1} @Thanks to Henry

Here the Code

    public static void main(String[] args) {

        int[] a = { 6, 8, 2, 4, 3, 1, 5, 7 };
        int max = Integer.MIN_VALUE;
        int second_max = Integer.MIN_VALUE;
        int temp;

        for (int i = 0; i < a.length; i++) {
            if (a[i] > max) {
                temp = max;
                max = a[i];
                second_max = temp;
            } else if (a[i] > second_max && a[i] != max) {
                second_max = a[i];
            }
        }
        if (second_max == Integer.MIN_VALUE) {
            System.out.println("No Second Highest value");
        } else {
            System.out.println(second_max);
        }
}

Output

7


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...