我是靠谱客的博主 欣喜芝麻,这篇文章主要介绍数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。,现在分享给大家,希望可以做个参考。

1.数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。

比如:输入一个长度为9的数组,(1,2,3,2,2,2,5,4,2),由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2,如果不存在,则输出0。
提示:Collections.sort()
实现代码如下:
1、

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class Getnum { public static void sort(int a[]) { int i,j,t; for(i=0;i<a.length-1;i++) { for(j=0;j<a.length-1-i;j++) if(a[j]>a[j+1]) { t=a[j]; a[j]=a[j+1]; a[j+1]=t; } } } public static void main(String args[]) { int i=1; int num=1; int a[]= {7,7,7,1,2,7,7,9,5}; sort(a); while(true) { if(i>a.length-1) { i=-1; break; } if(a[i-1]==a[i]) { num++; }else { num=1; } if(num>a.length/2) { break; } i++; } if(i==-1) { System.out.println(0); } else { System.out.println(a[i]); } } }

在这里插入图片描述
2、
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

最后

以上就是欣喜芝麻最近收集整理的关于数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。的全部内容,更多相关数组中有一个数字出现内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(89)

评论列表共有 0 条评论

立即
投稿
返回
顶部