O(n)時間內查找到無序數組當中的第二大元素

import java.util.Scanner;

public class SecondMAX {

	public static void main(String args[]) {
		System.out.println(new SecondMAX().getResult());
	}

	public int getResult() {
		int num, max, sec_max;
		Scanner sc = new Scanner(System.in);
		System.out.println("請輸入你要查找數組的元素個數:");
		num = sc.nextInt();
		int[] array = new int[num];
		for (int i = 0; i < num; i++) {
			array[i] = sc.nextInt();
		}
		max = sec_max = array[0];
		for (int i = 1; i < num; i++) {
			if (array[i] > max) {
				sec_max = max;
				max = array[i];
			}
		}
		return sec_max;
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章