众数
Description
给出N个1到30000间无序数正整数,其中1≤N≤10000,同一个正整数可能会出现多次,出现次数最多的整数称为众数。求出它的众数及它出现的次数。
Input
- 包含多组测试数据,每组测试数据包含2行。
- 第一行是正整数的个数N,第二行开始为N个正整数。
Output
每组测试数据输出有若干行,每行两个数,第1个是众数,第2个是众数出现的次数。
如有多个众数,按照从小到大的顺序输出。
Sample Input
12
2 4 2 3 2 5 3 7 2 3 4 3
Sample Output
2 4
3 4
代码实现
//法一:众数一定是出现次数大于n/2的元素,所以当对数组进行排列后,取其中间值,就是众数。
package com.company;
public class Mode {
public int majorityElement(int[] nums) {
int n = nums.length;
for(int i = 0 ;i< n;i++)
{
for(int j=0 ;j < n ;j++)
{
if(nums[i] > nums[j])
{
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
}
return nums[n/2];
}
}
//法二:利用哈希表的映射,映射数组中的数字以及它们出现的次数,当众数出现时,返回这个数字
package com.company;
public class Mode {
public int majorityElement(int[] nums) {
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
int n = nums.length;
for(int num : nums) //统计每个元素出现的次数
{
Integer count = map.get(num);
if(count == null)
count =1;
else
count++;
map.put(num,count);
if(map.get(num) > n/2)
return num;
}
return 0;
}
}