注意
由于Scanner会超时,这里我们使用BufferedReader和BufferedWriter
方法一:哈希统计出现的次数
直接使用HashMap统计出现的次数,然后再遍历一下哈希表,找到最大值,这个找到最大值的操作可以在put的时候进行。
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args)throws IOException{
Scanner sc = new Scanner(System.in);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
String[] strs = reader.readLine().split(" ");
int m = Integer.parseInt(strs[0]), n = Integer.parseInt(strs[1]);
Map<Integer,Integer> map = new HashMap<>();
int max = 0;
int res = 0;
for(int i = 0; i < n; i++){
strs = reader.readLine().split(" ");
for(int j = 0; j < m; j++){
int a = Integer.parseInt(strs[j]);
int cnt = map.getOrDefault(a,0);
map.put(a,cnt+1);
if(cnt + 1 > max){
max = cnt + 1;
res = a;
}
}
}
writer.write(res+"\n");
writer.flush();
reader.close();
writer.close();
}
}
方法二:栈
基本思路是如果栈为空的话,我们直接把当前元素入栈,栈不为空,那么我们比较栈顶元素和当前元素的值,如果值相等,那么直接入栈,如果值不相等,那么栈顶元素出栈.
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args)throws IOException{
Scanner sc = new Scanner(System.in);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
String[] strs = reader.readLine().split(" ");
int m = Integer.parseInt(strs[0]), n = Integer.parseInt(strs[1]);
int max = 0;
int res = 0;
Deque<Integer> stack = new LinkedList<>();
for(int i = 0; i < n; i++){
strs = reader.readLine().split(" ");
for(int j = 0; j < m; j++){
int a = Integer.parseInt(strs[j]);
if(stack.isEmpty()||stack.getLast()==a){
stack.addLast(a);
}else{
stack.removeLast();
}
}
}
writer.write(stack.removeLast()+"\n");
writer.flush();
reader.close();
writer.close();
}
}
方法三:使用常数个变量模拟栈的过程
由于栈中元素只是存储了一个相同的元素,那么我们只需要使用一个变量来记录这个元素出现的次数,然后使用一个变量记录栈中是哪个元素.
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args)throws IOException{
Scanner sc = new Scanner(System.in);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
String[] strs = reader.readLine().split(" ");
int m = Integer.parseInt(strs[0]), n = Integer.parseInt(strs[1]);
int cnt = 0;
int res = 0;
for(int i = 0; i < n; i++){
strs = reader.readLine().split(" ");
for(int j = 0; j < m; j++){
int a = Integer.parseInt(strs[j]);
if(cnt == 0){
cnt = 1;
res = a;
}else{
if(res == a){
cnt++;
}else{
cnt--;
}
}
}
}
writer.write(res+"\n");
writer.flush();
reader.close();
writer.close();
}
}