题目
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋
的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入:[3,2,3]
输出:3
示例 2:
输入:[2,2,1,1,1,2,2]
输出:2
进阶:
- 尝试设计时间复杂度为 O(n)、空间复杂度为 O(1) 的算法解决此问题。
解法
思路一: 使用哈希表。
class Solution {
// 使用HashMap解决
public int majorityElement(int[] nums) {
if(nums == null || nums.length == 0){
return 0;
}
Map<Integer,Integer> map = new HashMap<>();
for(int i = 0 ; i < nums.length ; i++){
int num = nums[i];
int count = map.get(num) == null ? 1 : map.get(num)+1;
map.put(num,count);
}
int n = nums.length / 2;
for(Map.Entry<Integer,Integer> entry : map.entrySet()){
Integer key = entry.getKey();
Integer value = entry.getValue();
if(value > n){
return key;
}
}
return 0;
}
}
思路二: 摩尔投票法。从第一个数开始count=1,遇到相同的就加1,遇到不同的就减1,减到0就重新换个数开始计数,总能找到最多的那个。
class Solution {
// 摩尔投票法
public int majorityElement(int[] nums) {
if(nums == null || nums.length == 0){
return 0;
}
int res = nums[0];
int count = 1;
for(int i = 1 ; i < nums.length ; i++){
if(count == 0){
res = nums[i];
}
count = res == nums[i] ? count+1 : count-1;
}
return res;
}
}
总结
本篇文章讲解了算法题目的思路和解法,代码和笔记由于纯手打,难免会有纰漏,如果发现错误的地方,请第一时间告诉我,这将是我进步的一个很重要的环节。以后会定期更新算法题目以及各种开发知识点,如果您觉得写得不错,不妨点个关注,谢谢。