当前位置:网站首页>输入n个整数,输出出现次数大于等于数组长度一半的数
输入n个整数,输出出现次数大于等于数组长度一半的数
2022-06-26 18:01:00 【一只懐坏旭】
牛客网·互联网名企笔试/面试题库
一,题目及描述:
输入n个整数,输出出现次数大于等于数组长度一半的数
输入描述:
每个测试输入包含 n个空格分割的n个整数,n不超过100,其中有一个整数出现次数大于等于n/2。
输出描述:
输出出现次数大于等于n/2的数。
二,示例
输入
3 9 3 2 5 6 7 3 2 3 3 3
输出
3
三,解题思路及代码
!!!!首先得注意只存在一个这样的数
思路1:
对输入序列进行排序,中间位置的元素即为出现现次数大于等于n/2的数
代码:
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String str = scanner.nextLine(); //输入接收为字符串,并且每个字符以空格隔开
String[] s = str.split(" "); //将字符串以空格拆分开
int[] arr = new int[s.length]; //准备一个数组
for (int i = 0; i < arr.length; i++) {
arr[i] = Integer.parseInt(s[i]); //将元素转换类型并移动到准备好的数组中
}
System.out.println(arr[arr.length/2]);//取出中间元素即可
}
}
}思路2:
利用Map统计每个元素的出现次数,输出Value大于等于n/2对应的key即可
代码:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
String str = scanner.nextLine(); //输入接收为字符串,并且每个字符以空格隔开
String[] s = str.split(" "); //将字符串以空格拆分开
Integer[] arr = new Integer[s.length]; //准备一个数组(Integer最好,int也可以,此时用Map,所以用包装类型避免拆箱)
for (int i = 0; i < arr.length; i++) {
arr[i] = Integer.parseInt(s[i]); //将元素转换类型并移动到准备好的数组中
}
Map<Integer,Integer> map = new HashMap<>();
for (int j = 0; j < arr.length; j++) {
//统计每个元素的个数
Integer count = map.get(arr[j]); //取出当前key,对应得Value
if(count == null){
map.put(arr[j],1); //如果是第一次放入,即Value置为1
} else {
map.put(arr[j],count+1);//否则在原来的基础+1
}
}
for(Map.Entry<Integer,Integer> entry : map.entrySet()){
//遍历Map找到大于等于数组长度一半的Value对应的key
if(entry.getValue() >= (arr.length/2)){
int x = entry.getKey();
System.out.println(x);
break;
}
}
}
}
}边栏推荐
- Chen Qiang: Alibaba's 100 billion level large-scale digital business knowledge map helps business growth
- MySQL的MVCC机制详解
- [npoi] C copy sheet template across workbooks to export Excel
- How to open a stock account? Is it safe to open an account online now?
- Leetcode HOT100 (22--- bracket generation)
- Li Kou daily question - day 28 -566 Reshape matrix
- 【万字总结】以终为始,详细分析高考志愿该怎么填
- Number of solutions for knapsack problem
- 在国金证券开户怎么样?开户安全吗?
- Please advise tonghuashun which securities firm to choose for opening an account? Is it safe to open an account online now?
猜你喜欢
随机推荐
【QNX】命令
17.13 补充知识、线程池浅谈、数量谈、总结
vutils.make_grid()与黑白图像有关的一个小体会
Connected to surface test questions
pycharm如何修改多行注释快捷键
Data Encryption Standard DES security
请指教同花顺开户选选择哪家券商比较好?现在在线开户安全么?
Uncover the secret of Agora lipsync Technology: driving portraits to simulate human speech through real-time voice
9、智慧交通项目(2)
Static registration and dynamic registration of JNI
LeetCode——226. 翻转二叉树(BFS)
map和filter方法对于稀缺数组的处理
RSA encryption and decryption details
RSA概念详解及工具推荐大全 - lmn
决策树与随机森林
Comp281 explanation
Digital signature standard (DSS)
Li Kou daily question - day 28 -566 Reshape matrix
#25class的类继承
Row lock analysis and deadlock









