数组中出现次数超过一半的数字
2020-10-13 14:04
113 查看
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为 9 的数组 {1,2,3,2,2,2,5,4,2},由于数字 2 在数组中出现了 5 次,超过数组长度的一半,因此输出 2。如果不存在则输出 0
解法一
对数组排序,如果符合条件的数存在,则一定是数组中间那个数。代码就不写了。
解法二
利用 Map 存值,找出存在最多的数字,若大于长度的一半,返回此数,否则返回 0
import java.util.Map; import java.util.HashMap; public class Solution { public int MoreThanHalfNum_Solution(int [] array) { if(array == null || array.length == 0) { return 0; } Map<Integer, Integer> map = new HashMap<>(); for(int i = 0; i < array.length; i++) { if(map.containsKey(array[i])) { map.put(array[i], map.get(array[i]) + 1); } else { map.put(array[i], 1); } } for(Map.Entry<Integer, Integer> entry : map.entrySet()) { if(entry.getValue() > (array.length / 2)) { return entry.getKey(); } } return 0; } }
解法三
注意到目标数超过数组长度的一半,如果对数组同时去掉两个不同的数字,到最后剩下的数就是该数字。实现的方式采用阵地攻守思想:
- 第一个数字作为第一个士兵,守阵地,count = 1
- 遇到相同元素,count++
- 遇到不相同元素,即为敌人,同归于尽,count--
- 遇到 count = 0 的情况,又以新的 i 值作为守阵地的士兵,继续下去,到最后还留在阵地上的士兵,有可能是我们希望的元素
- 再加一次循环,记录这个士兵的个数看是否大于数组一半即可
public class Solution { public int MoreThanHalfNum_Solution(int [] array) { if(array == null || array.length == 0) { return 0; } int val = array[0]; int count = 1; for(int i = 1; i < array.length; i++) { if(count == 0) { val = array[i]; count = 1; } else if(val == array[i]) { count++; } else { count--; } } count = 0; for(int i = 0; i < array.length; i++) { if(val == array[i]) { ad8 count++; } } return (count > array.length / 2) ? val : 0; } }
相关文章推荐
- 关于数组的问题(连续子数组的最大和、数组中出现次数超过一半的数字、调整数组顺序使奇数位于偶数之前)
- 基础题练习——数组中出现次数超过一半的数字
- 剑指offer——数组中出现次数超过一半的数字(不错,2 ways)
- 剑指offer---数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- [剑指Offer]数组中出现次数超过一半的数字
- 数组中有一个数字出现的次数超过了数组长度的一半,请找出这个数。java实现
- 数组中出现次数超过一半的数字
- P163、面试题29:数组中出现次数超过一半的数字
- 剑指offer_数组中出现次数超过一半的数字
- 《剑指Offer》学习笔记--面试题29:数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- AcWing 52 数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 剑指Offer对答如流系列 - 数组中出现次数超过一半的数字
- 算法题:数组中出现次数超过一半的数字
- 剑指offer 面试题29 数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字-基于Partitoin和数据规律
- 数组中出现次数超过一半的数字