如果数组中多一半的数都是同一个,则称之为主要元素。给定一个整数数组,找到它的主要元素。若没有,返回-1。
示例 1:
输入:[1,2,5,9,5,9,5,5,5] 输出:5
示例 2:
输入:[3,2] 输出:-1
示例 3:
输入:[2,2,1,1,1,2,2] 输出:2
说明:
你有办法在时间复杂度为 O(N),空间复杂度为 O(1) 内完成吗?
摩尔投票法。时间复杂度 O(n),空间复杂度 O(1)。
class Solution:
def majorityElement(self, nums: List[int]) -> int:
cnt = major = 0
for num in nums:
if cnt == 0:
major = num
cnt = 1
else:
cnt += (1 if major == num else -1)
return major
class Solution {
public int majorityElement(int[] nums) {
int cnt = 0, major = 0;
for (int num : nums) {
if (cnt == 0) {
major = num;
cnt = 1;
} else {
cnt += (major == num ? 1 : -1);
}
}
return major;
}
}
/**
* @param {number[]} nums
* @return {number}
*/
var majorityElement = function(nums) {
let cnt = 0;
let major = 0;
for (const num of nums) {
if (cnt == 0) {
major = num;
cnt = 1;
} else {
cnt += (major == num ? 1 : -1);
}
}
return major;
};
class Solution {
public:
int majorityElement(vector<int>& nums) {
int cnt = 0, major = 0;
for (int num : nums) {
if (cnt == 0) {
major = num;
cnt = 1;
} else {
cnt += (major == num ? 1 : -1);
}
}
return major;
}
};
public class Solution {
public int MajorityElement(int[] nums) {
int cnt = 0, major = 0;
foreach (int num in nums)
{
if (cnt == 0)
{
major = num;
cnt = 1;
}
else
{
cnt += (major == num ? 1 : -1);
}
}
return major;
}
}