题目
给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在众数。
示例 1:
输入: [3,2,3] 输出: 3
示例 2:
输入: [2,2,1,1,1,2,2] 输出: 2
第一时间想到了排序,因为排序后数字按顺序,直接可以比较是否相等,然后设置两个计数器,比大小,最后返回多的那一个。
写到中间发现还有优化办法,其实排序以后直接看出现的数字累计是否大于 一半,是直接返回,不是的话,等到切换数字,则计数器清0;
欠考虑的地方:没有考虑数组长度为1的情况,只有一个数字。
要认真读题,给定的数组总是存在众数
后来看到一个解法,亮瞎我眼了,排序后直接取中间那个数字,就是众数。
第一思路
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
if(nums.length == 1){//当数组长度为1
return nums[0];
}
int suma = 1,sumb = nums.length/2,number=0;
for(int i=1; i < nums.length; i++){
if(nums[i-1] == nums[i]){
suma++;
}
if(suma > sumb){//拿到目标数字 直接返回
number = nums[i-1];
return number;
}
if(nums[i-1] != nums[i]){//不相等 计数器重置1
suma = 1;
}
}
return number;
}
}
java和py的内置排序 是 O(nlgn)
下面是一个 for循环 O(n)
最终时间复杂度是 o(n) 空间消耗O(1)
其他解法:
1.哈希表,将数字作为key,出现次数作为value,出现大于数组一半的key,直接就输出
class Solution {
public int majorityElement(int[] nums) {
if(nums.length == 1){//当数组长度为1
return nums[0];
}
Map<Integer,Integer> map = new HashMap<>();
int target = nums.length/2;
int number = 0;
for(int num : nums){
if(map.containsKey(num)){
int count = map.get(num);
count++;
map.put(num,count);
if(count > target){
return num;
}
number = num;
}else{
map.put(num,1);//注意这里计数为1
}
}
return number;
}
}
2.Boyer-Moore 投票算法,这个是官方给的方法,我没有理解。
class Solution {
public int majorityElement(int[] nums) {
int count = 0;
Integer candidate = null;
for (int num : nums) {
if (count == 0) {
candidate = num;
}
count += (num == candidate) ? 1 : -1;
}
return candidate;
}
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/majority-element/solution/qiu-zhong-shu-by-leetcode-2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
复杂度分析
时间复杂度:O(n)O(n)
Boyer-Moore 算法严格执行了 nn 次循环,所以时间复杂度是线性时间的。
空间复杂度:O(1)O(1)
Boyer-Moore 只需要常数级别的额外空间。
这几天比较忙,算法刷的少了,工作中抽时间练习算法真的是海绵中挤时间,还要学习其他的东西,加油,向着心中的目标。