问题: 找出数组中重复次数最多的元素并打印
程序实现:
/**
* Copyright (c) 2011 Trusted Software and Mobile Computing(TSMC)
* All rights reserved.
* Author: Jarg Yee <yeshaoting@gmail.com>
* http://jarg.iteye.com/
*/
import java.util.*;
import java.util.Map.*;
/*
* 找出数组中重复次数最多的元素并打印
* ---------------------------------------------------------------------
* 1. 排序原始数组,采用二个变量记录相邻值不同的元素值,
* 二个变量记录相邻值不同的元素值出现次数
* 保留元素值出现次数多的那个,继续在原始数组中搜寻
* ---------------------------------------------------------------------
* 2. 定义一个数据结构,包含数组元素值和其出现次数
* 遍历数组,若数组元素不存在于该数据结构中,则添加并设置出现次数为1;
* 否则,修改该数据结构元素出现次数,次数+1
* 最后,遍历该数据结构,找出出现次数最多的元素.
*/
public class MostNum
{
/** for debugging. */
public static void main(String[] args)
{
int[] arr = {7,3,1,4,3,6,2,8,3,2,2,2,3,4,2};
if(arr.length==0)
{
System.out.println("等查找的数组为空.");
return;
}
method1(arr.clone());
method2(arr);
}
//method 1
public static void method1(int[] arr)
{
Arrays.sort(arr); //升序
//value,value_new值-1,为了使程序进入"不同元素值过渡"
int count=0, value=arr[0]-1; //保存最优元素信息
int count_new=0, value_new=arr[0]-1; //保存新搜寻元素信息
for(int i=0; i<arr.length; i++)
{
//连续相同的元素值
if(arr[i]==value_new)
{
count_new++;
}
//不同元素值过渡或者扫描到数组末尾
if(arr[i]!=value_new || i == arr.length-1)
{
//若新的元素值计数大于目前最优元素值计数时,更新
if(count_new>count)
{
count = count_new;
value = value_new;
}
//新的元素值
value_new = arr[i];
count_new = 1;
}
}
display(value, count);
}
//method 2
public static void method2(int[] arr)
{
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
//遍历数组,记录相同数组值出现次数并存储在数据结构中
for(int i=0; i<arr.length; i++)
{
if(map.containsKey(arr[i]))
map.put(arr[i], map.get(arr[i])+1);
else
map.put(arr[i], 1);
}
//遍历数据结构,找出出现次数最多的元素.
Set<Entry<Integer,Integer>> set = map.entrySet();
Iterator<Entry<Integer,Integer>> it = set.iterator();
boolean flag = true; //判断是否第一次迭代
int key = 0, value = 0;
while(it.hasNext())
{
Entry<Integer,Integer> e = it.next();
//第一次遍历数据结构,先初始化key,value
if(flag)
{
key = e.getKey();
value = e.getValue();
flag = false;
continue;
}
//当前元素出现次数大于当前最优值的情况
if(e.getValue()>value)
{
key = e.getKey();
value = e.getValue();
}
}
display(key, value);
}
//显示结果
public static void display(int key, int value)
{
System.out.println("重复次数最多元素:" + key + "\t重复次数:" + value);
}
}