接下来要给大家带来的是找出数组中出现的次数超过数组长度的一半的一个数字的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实例,欢迎大家继续来本站了解哦。