169. Majority Element
2017-03-18 09:10
176 查看
Given an array of size n, find the majority element. The majority element is the element that appears more than
You may assume that the array is non-empty and the majority element always exist in the array.
1. 首先用hashmap
hashmap中先写 !map.containsKey() 比 map.containsKey() 的速度快一倍
if(nums.length == 0 && nums == null) return 0;
Map<Integer,Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
if(!map.containsKey(nums[i])) {
map.put(nums[i], 1);
} else {
map.put(nums[i], map.get(nums[i]) + 1);
}
}
int c= 0;
for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
if(entry.getValue() > (nums.length/2) ) c = entry.getKey();
}
return c;
⌊ n/2 ⌋times.
You may assume that the array is non-empty and the majority element always exist in the array.
1. 首先用hashmap
hashmap中先写 !map.containsKey() 比 map.containsKey() 的速度快一倍
if(nums.length == 0 && nums == null) return 0;
Map<Integer,Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
if(!map.containsKey(nums[i])) {
map.put(nums[i], 1);
} else {
map.put(nums[i], map.get(nums[i]) + 1);
}
}
int c= 0;
for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
if(entry.getValue() > (nums.length/2) ) c = entry.getKey();
}
return c;
相关文章推荐
- ※ Leetcode - Array - 169. Majority Element(快速找出数组中出现过一半以上次数的数,3种写法)
- 【LeetCode】169.Majority Element (Easy)
- 169. Majority Element
- Leetcode 169, 229 Majority element
- Leetcode-169 Majority Element
- leetoce(43).169. Majority Element
- Leetcode 169 Majority Element
- [leetcode 169. Majority Element]easy |week4
- 169. Majority Element
- leetcode169. Majority Element
- 169. Majority Element -- 字典
- [leetcode] Add to List 169. Majority Element
- leetcode 169 Majority Element 冰山查询
- [leetcode]#169. Majority Element
- 169 Majority Element
- 169.Majority Element (数组中出现次数超过一半的数)
- 【LeetCode】169 - Majority Element
- 169. Majority Element
- Leetcode # 169 Majority Element
- 2018.03.07 leetcode 打卡 #169. Majority Element