您的位置:首页 > 其它

169. Majority Element

2017-02-21 01:24 316 查看
题目:

Given an array of size n, find the majority element. The majority element is the element that appears more than
⌊ n/2 ⌋
times.

You may assume that the array is non-empty and the majority element always exist in the array.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

链接: http://leetcode.com/problems/majority-element/

2/20/2017, Java

performance不好,为什么?

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


因为有Boyer-Moore Majority vote algorithm!

留给二刷,并且要学会多于特定比例的情况。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: