众数问题

众数问题算法有很多实现,众数问题的实现选择要考虑多个方面,这里用到了快速排序算法思想,将每次递归计数到返回值Map里,再与之比较
 
 
public class ModeAlgorithmT {
	private int[] arrTemp;

	public ModeAlgorithmT(int[] arr) {
		// TODO Auto-generated constructor stub
		this.arrTemp = arr;
		Map<Integer, Integer> xx = quickSort(arrTemp, 0, arr.length - 1);
		Iterator it = xx.keySet().iterator();
		int key, count = 0, mode = 0;
		while (it.hasNext()) {
			key = Integer.parseInt(it.next().toString());
			if (xx.get(key) > count) {
				mode = key;
				count = xx.get(key);
			}
			System.out.println(xx.size());
		}
		System.out.println("众数是" + mode);
		System.out.println("重数是" + count);

	}

	public Map<Integer, Integer> quickSort(int[] arr, int lowIndex,
			int highIndex) {
		int low = lowIndex;
		int high = highIndex;
		Map<Integer, Integer> xx = new HashMap<Integer, Integer>();

		int mid = 0, count = 0;
		if (highIndex > lowIndex) {
			mid = arr[lowIndex + (highIndex - lowIndex) / 2];
			while (low <= high) {
				while ((low < highIndex) && (arr[low] < mid)) {
					++low;
				}
				while ((high > lowIndex) && (arr[high] > mid)) {
					--high;
				}
				if (low <= high) {
					int temp = arr[low];
					arr[low] = arr[high];
					arr[high] = temp;
					++low;
					--high;
				}
				if (high != low) {		//避免重复计数
					if (arr[high] == mid) {
						count++;
					}
					if (arr[low] == mid) {
						count++;
					}
				} else {
					if (arr[high] == mid) {
						count++;
					}
				}
			}
			if (lowIndex < high) {
				Map<Integer, Integer> temp = quickSort(arr, lowIndex, high);
				int key = temp.keySet().iterator().next();
				if (temp.get(key) > count) {
					count = temp.get(key);
					mid = key;
				}
			}
			if (low < highIndex) {
				Map<Integer, Integer> temp = quickSort(arr, low, highIndex);
				int key = temp.keySet().iterator().next();
				if (temp.get(key) > count) {	//比较递归调用返回的重数与众数
					count = temp.get(key);
					mid = key;
				}
			}
		}
		xx.put(mid, count);		//存入当前众数与重数
		return xx;
	}
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值