"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?
OutputFor 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 1Sample Output
3 5 1
Topic link: https://vjudge.net/contest/225380#problem/B
The general meaning of the question is, to give you N numbers, you need to find the number of occurrences >= (N+1)/2. Since the number of occurrences is more than half, there must be only one and only one of this number.
My problem-solving idea is to traverse all the numbers and find the number with the largest number of occurrences (because the input test case will definitely have the number of occurrences that meet the requirements, so regardless of the input situation that does not meet the requirements, directly find the number with the largest number of occurrences ). Scan from right to left, first assign the value of the first scan to the result variable, and the count variable count is 1. Continue to scan, if the current scanned value is not result, count--, if equal, count++, if count is 0, assign the current scanned value to result, count++. At the end of the scan, the value saved in result is the answer.
Note: Due to the large number of input data groups, the input and read data must be fast. It is recommended to use the StreamTokenizer reading method.
The event complexity of this method is n, and the space complexity is negligible. 400ms for AC
Attached reference code:
package acm; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StreamTokenizer; /** * Ignatius * create by chenshihang on 2018/5/2 */ public class Ignatius { public static void main(String[] args) throws IOException { StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); while(in.nextToken()!=StreamTokenizer.TT_EOF){ int N = (int)in.nval; int count = 0; int result = 0; for(int i=0;i<N;i++){ in.nextToken(); int a=(int)in.nval; if(i==0){ count++; result=a; }else{ if(count==0){ result=a; count++; }else { if(a==result){ count++; }else { count--; } } } } System.out.println(result); } } }