剑指offer-面试题29-数组中出现次数超过一半的数字

解法一:基于partition函数的O(n)算法
数组中有一个数字出现的次数超过了数组长度的一半。如果把这个数组排序,那么排序之后位于数组中间的数字一定就是那个出现次数超过数组长度一半的数字。也就是说,这个数字就是统计学上的中位数,即长度为n 的数组中第n/2 大的数字。

这种算法是受快速排序算法的启发。在随机快速排序算法中,我们先在数组中随机选择一个数字,然后调整数组中数字的顺序, 使得比选中的数字小数字都排在它的左边,比选中的数字大的数字都排在它的右边。如果这个选中的数字的下标刚好是n/2,那么这个数字就是数组的中位数。如果它的下标大于n/2 ,那么中位数应该位于它的左边,我们可以接着在它的左边部分的数组中查找。如果它的下标小于n/2,那么中位数应该位于它的右边,我们可以接着在它的右边部分的数组中查找。这是一个典型的递归过程。
package case29_MoreThanHalfNum;

/**
 * 题目:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。
 * 由于数字2在数组中出现5次,超过数组长度的一半,一次输出2。异常处理,不满足条件时输出-1
 * 
 * @author WangSai
 *
 */

public class MoreThanHalfNum {
	/**
	 * @param 输入的数组 array[]
	 * @return 满足条件的数字
	 */
	public static void main(String[] args) {
		int[] arr0 = { 1, 3, 3 };
		int[] arr1 = {  };
		System.out.println(MoreThanHalf1(arr0));
		System.out.println(MoreThanHalf1(arr1));
	}

	// 基于Partition函数的O(n)算法
	private static int MoreThanHalf1(int[] arr) {
		// 检测异常情况
		if ((arr == null)||(arr.length < 1))
			throw new RuntimeException("输入的数组无效...");
		// 获得数组的中间坐标
		int middle = arr.length >> 1;
		// 通过partition完成数字的输出任务。
		int low = 0;
		int high = arr.length - 1;
		int index = partition(arr, low, high);
		while (index != middle) {
			if (index < middle) {
				low = index + 1;
				index = partition(arr, low, high);
			} else {
				high = index - 1;
				index = partition(arr, low, high);
			}
		}
		int result = arr[index];
		// 检测该数字出现次数是否超过一半,如果满足则放回该数字;否则,报错
		result = checkMoreThanHalf(arr, result);
		return result;
	}

	// 检测某数字在对应的数组中出现次数是否超过一半
	private static int checkMoreThanHalf(int[] arr, int result) {
		int times = 0;
		for (int i = 0; i < arr.length; i++) {
			if (arr[i] == result)
				times++;
		}
		if(times * 2 > arr.length)
			return result;
		else 
			throw new RuntimeException("输入的数组无效...");
	}

	// Partition选择一个数,通过一定方法,使得该数字左侧的数字都比其小,右侧数字比其要大。返回该数字所在的位置。
	private static int partition(int[] arr, int low, int high) {
		int pivotKey = arr[low];
		while (low < high) {
			while (low < high && arr[high] >= pivotKey)
				high--;
			arr[low] = arr[high];
			while (low < high && arr[low] <= pivotKey)
				low++;
			arr[high] = arr[low];
		}
		arr[low] = pivotKey;
		return low;
	}
}


解法二:根据数组特点找出O(n)的算法
数组中有一个数字出现的次数超过数组长度的一半,也就是说它出现的次数比其他所有数字出现次数的和还要多。因此我们可以考虑在遍历数组的时候保存两个值: 一个是数组中的一个数字, 一个是次数。当我们遍历到下~个数字的时候,如果下一个数字和我们之前保存的数字相同,则次数加l :如果下一个数字和我们之前保存的数字,不同,则次数减1 。如果次数为霉,我们需要保存下一个数字,并把次数设为1 。由于我们要找的数字出现的次数比其他所有数字出现的次数之和还要多,那么要找的数字肯定是最后一次把次数设为1 时对应的数字。
package case29_MoreThanHalfNum;

/**
 * 题目:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。
 * 由于数字2在数组中出现5次,超过数组长度的一半,一次输出2。异常处理,不满足条件时输出-1
 * 
 * @author WangSai
 *
 */
public class MoreThanHalfNum2 {
	/**
	 * @param 数组
	 * @return 出现次数超过数组一半的数字
	 */
	public static void main(String[] args) {
		int[] arr = { 1, 2, 3, 3 };
		System.out.println(moreThanHalf(arr));
	}

	// 出现次数超过数组一半的数字
	private static int moreThanHalf(int[] arr) {
		// 检测异常情况
		if (arr == null || arr.length <= 0)
			throw new RuntimeException("输入的数组非法...");
		// 假设arr[0]就是次数超过一半的值
		int result = arr[0];
		// 记录出现的次数
		int times = 1;
		// 过滤掉出现次数低于一半的数
		for (int i = 1; i < arr.length; i++) {
			if (times == 0) {
				result = arr[i];
				times = 1;
			} else if (arr[i] == result) {
				times++;
			} else {
				times--;
			}
		}
		return checkMoreThanHalf(arr, result);
	}

	// 检测输入获得的数字的次数,是否超过数组长度的一半。
	private static int checkMoreThanHalf(int[] arr, int result) {
		int times = 0;
		for (int j = 0; j < arr.length; j++) {
			if (arr[j] == result)
				times++;
		}
		if (times * 2 > arr.length)
			return result;
		else
			// return -1;
			throw new RuntimeException("输入的数组非法...");
	}

}


解法三:利用map集合的O(n)算法
直接用哈稀表来存储<key, value>,并找出出现次数value大于等于一半的那个key。

package case29_MoreThanHalfNum;

import java.util.HashMap;

public class ByHashMap {

	public static void main(String[] args) {
		int[] arr = { 1, 2, 3, 3, 3 };
		System.out.println(moreThanHalf(arr));
	}

	// 出现次数超过一半的数字
	private static int moreThanHalf(int[] arr) {
		if (arr == null || arr.length <= 0)
			throw new RuntimeException("输入的数组非法...");
		// 创建map集合
		HashMap<Integer, Integer> hp = new HashMap<>();
		// 把出现的数字和该数字出现的次数分别作为键和值,存储到map中
		for (int j = 0; j < arr.length; j++) {
			if (!hp.containsKey(arr[j]))
				hp.put(arr[j], 1);
			else {
				hp.put(arr[j], hp.get(arr[j]) + 1);
			}
		}
		// 迭代
		for (Integer key : hp.keySet()) {
			// System.out.println(hp.get(key));
			if (hp.get(key) >= arr.length / 2)
				return key;
		}
		throw new RuntimeException("输入的数组非法......");

	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值