您的位置:首页 > 其它

169 Majority Element

2015-07-27 23:07 603 查看
题目链接:https://leetcode.com/problems/majority-element/

题目:

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.


解题思路:

每次找出两个不同的元素删除,最后剩下的就是超过一半的元素。即:和其它元素对消后,还有剩余的元素就是多数元素。

注意:

如果题目要求是⌊ n/k ⌋,则每次找出 k 个不同的元素来消除。

public class Solution {
public int majorityElement(int[] nums) {
int n = nums.length;
int ret = nums[0];
int count = 1;
for(int i = 1; i < n; i ++) {
if(ret == nums[i])
count ++;
else {
count --;
if(count == 0) {
ret = nums[i];
count = 1;
}
}
}
return ret;
}
}


42 / 42 test cases passed.
Status: Accepted
Runtime: 432 ms


方法二:自己想出的方法

解题思路:

将每一个元素看做一个键存入hashMap,对应的键值为该元素出现的次数。遍历完数组后,遍历hashMap,判断元素出现的次数是否大于n / 2。

public class Solution {
public int majorityElement(int[] nums) {
int n = nums.length;
HashMap<Integer, Integer> map = new HashMap();
for(int i = 0; i < n; i ++) {
int k = nums[i];
if(!map.containsKey(k))
map.put(k, 1);
else
map.put(k, map.get(k) + 1);
}
int majorityE = Integer.MIN_VALUE;
for(Map.Entry<Integer, Integer> m : map.entrySet()) {
int times = m.getValue();
if(times > n / 2) {
majorityE = m.getKey();
break;
}
}
return majorityE;
}
}


42 / 42 test cases passed.
Status: Accepted
Runtime: 496 ms
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: