HDU1026 Ignatius and the Princess IV(java)

Problem Description
“OK, you are not too bad, em… But you can never pass the next test.” feng5166 says.

“I will tell you an odd number N, and then N integers. There will be a special integer among them, you have to tell me which integer is the special one after I tell you all the integers.” feng5166 says.

“But what is the characteristic of the special integer?” Ignatius asks.

“The integer will appear at least (N+1)/2 times. If you can’t find the right integer, I will kill the Princess, and you will be my dinner, too. Hahahaha…..” feng5166 says.

Can you find the special integer for Ignatius?

Input
The input contains several test cases. Each test case contains two lines. The first line consists of an odd integer N(1<=N<=999999) which indicate the number of the integers feng5166 will tell our hero. The second line contains the N integers. The input is terminated by the end of file.

Output
For each test case, you have to output only one line which contains the special number you have found.

Sample Input
5
1 3 2 3 3
11
1 1 1 1 1 5 5 5 5 5 5
7
1 1 1 1 1 1 1

Sample Output
3
5
1
題意是要在奇數個數中找到重複一半以上的數。需要注意的是由於輸入的數字個數較多,使用數組存儲輸入會造成內存使用量過大。

分析:在一個數列中,去掉兩個不同的數,原數列中出現次數不小於(N+1)/2的數字在新序列中出現的次數依舊不小於(N - 2 +1)/2,也就說原序列中的解再去掉兩個不同數字後依舊是新序列的解。
依據上述的思想,使用計數器cnt,結果變量result(存儲數列中的元素),依次掃描數列中的數,如果當前掃描的數和result相同,則cnt++,否則cnt–,當cnt=0的時候,result代表的數肯定不滿足要求;這時將數列中下一個元素賦值給result並設置cnt=1,重複此過程直至結束,result的值就是所滿足要求的數。
下面的代碼提交到OJ上運行超時,也不知道是爲什麼,程序結構已經很簡單了,難道是scanner的原因,可是不用scanner又要使用什麼呢?

import java.util.Scanner;

public class P1029 {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n, cur, result = 0, cnt;
        while (scanner.hasNextInt()) {
            n = scanner.nextInt();
            cnt = 0;
            for (int i = 0; i < n; i++) {
                cur = scanner.nextInt();
                if(cnt == 0){
                    result = cur;
                    cnt = 1;
                }else if(cur != result){
                    cnt--;
                }else if(cur == result){
                    cnt++;
                }
            }
            System.out.println(result);
        }
        scanner.close();
    }

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