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();
    }

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