找出陣列中第二大的數字

package algorithm;

public class NumberInArray {

    public static int findSecondNumber(int[] arr) {

        int max =  Integer.MIN_VALUE;
        int second = Integer.MIN_VALUE;

        for(int i=0; i<arr.length;i++) {
            int n = arr[i];
            if(n>max) {
                second = max;
                max = n;
            } else if (n>second){
                second = n;
            }
        }
        return second;
    }

    public static void main(String[] args){
        int[] arr = new int[] {1,5,20,30,46,55,70,100};
        int rs = findSecondNumber(arr);
        System.out.println("outcome:"+rs);
    }
}

results matching ""

    No results matching ""