Problem
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.
Solution
class Solution {
public int majorityElement(int[] nums) {
if (nums == null || nums.length == 0) return -1;
Map<Integer, Integer> map = new HashMap<>();
for (int num: nums) {
if (map.containsKey(num)) {
if (map.get(num)+1 > nums.length/2) {
return num;
} else {
map.put(num, map.get(num)+1);
}
} else {
map.put(num, 1);
}
}
return -1;
}
}
update 2018-11
class Solution {
public int majorityElement(int[] nums) {
int count = 0;
int res = nums[0];
for (int num: nums) {
if (count == 0) {
res = num;
count++;
} else if (num == res) {
count++;
} else {
count--;
}
}
return res;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。