[编程题]-n个数里出现次数大于等于n/2的数
【解题思路】:
关键方法:
str.split(" "):
按照空格切分字符串
Integer.valueOf(str):
将数字字符串转为
int
【示例代码】:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
String str = in.nextLine();
String[] strs = str.split(" ");
int[] arr = new int[strs.length];
for (int i = 0; i < arr.length; i++) {
arr[i] = Integer.valueOf(strs[i]);
}
int num = arr[0];
int count = 0;
for (int j = 1; j < arr.length; j++) {
if (arr[j] == num) {
count++;
} else if (count > 0) {
count--;
} else {
num = arr[j];
}
}
System.out.println(num);
}
}
}