数组中出现次数超过一半的数字

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。

 1 # -*- coding:utf-8 -*-
 2 class Solution:
 3     def MoreThanHalfNum_Solution(self, numbers):
 4         n = len(numbers)
 5         if n == 0:
 6             return 0
 7         half = n // 2
 8         dic = {}
 9         for n in numbers:
10             if n in dic:
11                 dic[n] += 1
12             else:
13                 dic[n] = 1
14             if dic[n] > half:
15                 return n
16         return 0
17         # write code here

 

java版代码,leetcode地址:

 1 public int majorityElement(int[] nums) {
 2         HashMap<Integer, Integer> hMap = new HashMap<Integer, Integer>();
 3         int n = nums.length;
 4         for (int i = 0; i < n; i++) {
 5             if (hMap.containsKey(nums[i])) {
 6                 int times = hMap.get(nums[i]).intValue();
 7                 times++;
 8                 if (times > n / 2) {
 9                     return nums[i];
10                 }
11                 hMap.put(nums[i], times);
12             }
13             else {
14                 hMap.put(nums[i], 1);
15             }
16         }
17         return nums[0];
18     }

 

posted on 2019-06-13 09:16  Sempron2800+  阅读(121)  评论(0编辑  收藏  举报