(剑指offer)数组中出现次数超过一半的数字
2017-09-11 15:30
218 查看
题目:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
代码如下:
结果如下:
代码如下:
public class MoreThanHalfNum { public static void main(String[] args) { int[] array = { 1, 2, 3, 2, 2, 2, 5, 4, 2 }; int results = MoreThanHalfNum_Solution(array); System.out.println("超过数组长度一半的数字为:" + results); } public static int MoreThanHalfNum_Solution(int[] array) { if (array.length < 0 || array == null) { return 0; } int result = array[0]; int times = 1; for (int i = 1; i < array.length; i++) { if (times == 0) { result = array[i]; times = 1; } else if (array[i] == result) { times++; } else { times--; } } int count = 0; for (int i = 0; i < array.length; i++) { if (array[i] == result) { count++; } } if (count * 2 > array.length) { return result; } return 0; } }
结果如下:
相关文章推荐
- 剑指offer(30):数组中出现次数超过一半的数字
- 剑指Offer——(28)数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字——剑指offer
- 剑指Offer——数组中出现次数超过一半的数字
- 剑指offer(25)-数组中出现次数超过一半的数字
- 剑指Offer(java版):数组中出现次数超过一半的数字
- [置顶] 剑指offer:第29题寻找数组中出现次数超过一半的数字
- 剑指offer——数组中出现次数超过一半的数字
- 剑指offer——数组中出现次数超过一半的数字
- 剑指Offer_面试题29_数组中出现次数超过一半的数字
- 剑指Offer面试题29(java版):数组中出现次数超过一半的数字
- 剑指offer-----面试题29(数组中出现次数超过一半的数字)
- 剑指offer:数组中出现次数超过一半的数字
- 剑指offer——面试题29:数组中出现次数超过一半的数字
- 剑指Offer:数组中出现次数超过一半的数字
- 《剑指offer》面试题29:数组中出现次数超过一半的数字
- 《剑指Offer》数组中出现次数超过一半的数字
- 算法系列——数组中出现次数超过一半的数字(剑指offer)
- 剑指offer(28)—数组中出现次数超过一半的数字
- 剑指Offer面试题29(java版):数组中出现次数超过一半的数字