var majorityElement = function (nums) {
let middle = nums.length >> 1;
let map = new Map();
for (let i = nums.length - 1; i >= 0; i--) {
if (!map.has(nums[i])) {
map.set(nums[i], 1);
} else {
map.set(nums[i], map.get(nums[i]) + 1);
}
}
for (const [key, value] of map) {
if (value > middle) return key;
}
return -1;
};
console.assert(majorityElement([1, 2, 5, 9, 5, 9, 5, 5, 5]) === 5);
console.assert(majorityElement([3, 2]) === -1);
console.assert(majorityElement([2, 2, 1, 1, 1, 2, 2]) === 2);
时间复杂度:O(n), 空间复杂度:O(1)
var majorityElement = function (nums) {
let middle = nums.length >> 1;
let candidate,
counter = 0;
for (let i = 0, len = nums.length; i < len; i++) {
if (counter === 0) {
candidate = nums[i];
counter++;
} else {
if (nums[i] === candidate) {
counter++;
} else {
counter--;
}
}
}
if (counter) {
counter = 0; // 清零用于统计candidate票数
for (let i = nums.length - 1; i >= 0; i--) {
if (nums[i] === candidate) counter++;
}
if (counter > middle) {
return candidate;
}
}
// console.log('candidate ', candidate, counter);
return -1; // 不存在
};
console.assert(majorityElement([1, 2, 5, 9, 5, 9, 5, 5, 5]) === 5);
console.assert(majorityElement([3, 2]) === -1);
console.assert(majorityElement([2, 2, 1, 1, 1, 2, 2]) === 2);
As we sweep we maintain a pair consisting of a current candidate and a counter.
Initially, the current candidate is unknown and the counter is 0.
When we move the pointer forward over an element e:
If the counter is 0, we set the current candidate to e and we set the counter to 1.
If the counter is not 0, we increment or decrement the counter according to whether e is the current candidate.
When we are done, the current candidate is the majority element, if there is a majority.
演示网站:https://www.cs.utexas.edu/~moore/best-ideas/mjrty/index.html
时间复杂度:O(n), 空间复杂度:O(1)