题目描述
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: [3,2,3]
输出: 3
示例 2:
输入: [2,2,1,1,1,2,2]
输出: 2
题解
1. 暴力法
利用count函数可以返回数组中元素出现的次数 n n n,如果 n > s i z e / 2 n>size/2 n>size/2,返回这个元素。
class Solution {
public:
int majorityElement(vector<int>& nums) {
int len = nums.size();
for (int i=0;i<len;i++){
int num = count(nums.begin(),nums.end(),nums[i]);
if (2*num>len){
return nums[i];
}
}
return -1;
}
};
时间复杂度:count进行一次循环遍历,外层又进行了一次循环遍历,时间复杂度为 O ( n 2 ) O(n^2) O(n2)
摩尔投票法
- 初始化candidate为任意值,count=0
- 遍历数组,当前元素为
x
x
x:
- 如果count=0,令candidate= x x x,count=1
- 如果 x x x=candidate,则count+1
- 如果 x x x!=candidate,则count-1
- 最终candidate就是众数
因为众数的数量大于其他任何数,所以无论怎么-1,众数的count总不为0
//c++
class Solution {
public:
int majorityElement(vector<int>& nums) {
int candidate = -1;
int count = 0;
for (int num : nums) {
if (num == candidate)
++count;
else if (--count < 0) {
candidate = num;
count = 1;
}
}
return candidate;
}
};
//go
func majorityElement(nums []int) int {
candidate := nums[0]
count := 0 //多数元素初始计数为0
for i := 0; i < len(nums); i++ {
//若计数为0,则认为当前元素就是多数元素
if count == 0 {
candidate = nums[i]
}
//当前元素为多数元素时计数加一,否则减一
if nums[i] != candidate {
count--
} else {
count++
}
}
return candidate
}
时间复杂度:
O
(
n
)
O(n)
O(n)
空间复杂度:
O
(
1
)
O(1)
O(1)