数组:数组中出现次数超过一半的数字
2020-04-05 18:25
447 查看
题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
思路分析
三种解法:
法1:使用HashMap存储,key是数组值,value是出现次数,全部存入后再for循环比较value*2是否大于length;
法2:排序。数组排序后,如果某个数字出现次数超过数组的长度的一半,则一定会数组中间的位置。所以我们取出排序后中间位置的数,统计一下它的出现次数是否 大于数组长度的一半;
参考代码
法1:运行时间:19ms 占用内存:9416k
1 import java.util.HashMap; 2 import java.util.Map; 3 public class Solution { 4 public int MoreThanHalfNum_Solution(int [] array) { 5 HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); 6 int length = array.length; 7 for(int i = 0; i < length; i++) { 8 if(!map.containsKey(array[i])) { 9 map.put(array[i], 1); 10 } else { 11 map.put(array[i], map.get(array[i]) + 1); 12 } 13 } 14 for(Map.Entry<Integer, Integer> m : map.entrySet()) { 15 if(m.getValue() * 2 > length) { 16 return m.getKey(); 17 } 18 } 19 return 0; 20 } 21 }View Code
法2:运行时间:15ms 占用内存:9336k
1 import java.util.Arrays; 2 public class Solution { 3 public int MoreThanHalfNum_Solution(int [] array) { 4 Arrays.sort(array); 5 int half = array.length / 2; 6 int count = 0; 7 for(int i = 0; i < array.length; i++) { 8 if(array[i] == array[half]) { 9 count++; 10 } 11 } 12 if(count > half) { 13 return array[half]; 14 } else { 15 return 0; 16 } 17 } 18 }View Code
转载于:https://www.cnblogs.com/carry6/p/11518049.html
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- 剑指offer系列之27:数组中出现次数超过一半的数字
- 《剑指offer》数组中出现次数超过一半的数字
- 数组中超过出现次数超过一半的数字
- 数组中出现次数超过一半的数字(剑指offer)
- 面试题29:数组中出现次数超过一半的数字
- 数组中有一个数字出现的次数超过了数组长度的一半,找出这个数
- 数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字。
- 剑指offer面试题29:数组中出现次数超过一半的数字
- 剑指Offer--【数组中出现次数超过一半的数字】--java
- 剑指Offer_28_数组中出现次数超过一半的数字
- 每日一道算法题:数组中出现次数超过一半的数字
- 关于数组的问题(连续子数组的最大和、数组中出现次数超过一半的数字、调整数组顺序使奇数位于偶数之前)
- 【剑指offer】面试题39:数组中出现次数超过一半的数字
- 剑指offer-29:数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 出现次数超过数组长度一半的数字
- [剑指Offer] 28.数组中出现次数超过一半的数字