求数组出现次数前n个数JAVA_找出数组中出现次数超过数组长度一半的数字java实现...

接下来要给大家带来的是找出数组中出现的次数超过数组长度的一半的一个数字的java实现和思路,一起来看看吧。

题目:

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

例:

输入一个长度为9的数组{1,2,3,2,2,2,5,4,2},因为,数字2在数组当中出现了5次,并且,超过了数组长度的一半,所以,输出2。

假如不存在那么就输出0。

思路1

代码实现:class Solution

{

public:

int MoreThanHalfNum_Solution(vector  numbers)

{

int n = numbers.size();

if (n == 0) return 0;

int num = numbers[0], count = 1;

for (int i = 1; i 

{

if (numbers[i] == num) count++;

else count--;

if (count == 0)

{

num = numbers[i];

count = 1;

}

}

// Verifying

count = 0;

for (int i = 0; i 

{

if (numbers[i] == num) count++;

}

if (count * 2 > n) return num;

return 0;

}

};

思路2:

利用map存值,找出存在最多的数字,假如大于长度一半,返回此数,否则返回0

代码实现:public class Solution

{

public int MoreThanHalfNum_Solution(int[] array)

{

if (array.length == 0 || array == null)

return 0;

Map  map = new HashMap  ();

for (int i = 0; i 

{

if (map.containsKey(array[i]))

{

map.put(array[i], map.get(array[i]) + 1);

}

else

{

map.put(array[i], 1);

}

}

for (Map.Entry  entry: map.entrySet())

{

if (entry.getValue() > array.length / 2)

return entry.getKey();

}

return 0;

}

}

思路3:

用一个数组为每个数字设置一个计数器,在计数值超过数组长度一半则返回该数字。

假如遍历整个数字后仍无此种数值,那么返回0。

代码实现:public class Solution

{

public int MoreThanHalfNum_Solution(int[] array)

{

int len = array.length;

int[] count = new int[]

{

0

, 0

, 0

, 0

, 0

, 0

, 0

, 0

, 0

, 0

};

for (int i = 0; i 

{

count[array[i]]++;

if ((count[array[i]] * 2) > len)

{

return array[i];

}

}

return 0;

}

}

java实现有很多方式,更多的Java实例,欢迎大家继续来本站了解哦。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值