Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
先列一个最容易想到的js方法:
/**
* @param {number[]} nums
* @return {number}
*/
var majorityElement = function(nums) {
var threshold = Math.floor(nums.length/2);
var obj = {};
for (var i=0; i<nums.length; i++){
if (typeof obj[nums[i]] == 'undefined') {
obj[nums[i]] = 1;
} else {
obj[nums[i]] = obj[nums[i]] + 1;
}
}
for (j in obj) {
if (obj[j] > threshold ) {
return j;
}
}
return null;
};
另外一种推荐的js方法:
/**
* @param {number[]} nums
* @return {number}
*/
var majorityElement = function(nums) {
var major=nums[0], count = 1;
var num_length = nums.length;
for(var i=1; i<num_length;i++){
if(count==0){
count++;
major=nums[i];
}else if(major==nums[i]){
count++;
}else count--;
console.log(nums[i]+'========='+count);
if (count > num_length -i -1) return nums[i]
}
return major;
};
参考下; https://leetcode.com/problems/majority-element/discuss/51613/O(n)-time-O(1)-space-fastest-solution中的评论来解释后一种解法。
Eventually, non-majority elements whose count
is less than ⌊ n/2 ⌋
will not be kept in major
, because there exist more elements different to the non-majority elements that makes count
less than 0 by
if(count==0){
count++;
major=num[i];
}else if(major==num[i]){
count++;
}else count--;
More specifically, since the majority
appears more than ⌊ n/2 ⌋
, let's define numbers that are different to majority
as diff_majority
, the number of diff_majority
(num_diff_majority
) is less than the number of majority
(num_majority
). For any majority
, we can get other majority
ies with the number of at least ⌊ n/2 ⌋
, so the total num_diff_majority
would be less than ⌊ n/2 ⌋
. Then by the code above, if the current variable major
is diff_majority
, eventually it will be replaced with other numbers because more majority
will makes count
less than 0 by count--
. In the end, the variable major
will store the number appearing more than ⌊ n/2 ⌋
.
总得意思就是 既然 主要元素的定义是要超过元素总数半数,那么剩余的元素总和必定小于半数。可以把非主要元素想像成一个同一个变量。遍历到非主要元素时,由于非主要元素的个数小于半数,最终会退化为0.
对方法2 进行简短的测试:
var major = majorityElement([1,2,1,2,2,3,1,2,2]);
console.log('major is.....' + major);
结果如下:
2=========0
1=========1
2=========0
2=========1
3=========0
1=========1
2=========0
2=========1
major is.....2
值得注意的是题目中假设的是数组不为空,且占到数组长度一般的数一定存在。所以测试用例也必须满足这个条件。