Input: [3,2,3]
Output: [3]
Input: [1,1,1,3,3,2,2,2]
Output: [1,2]
var majorityElement = function(nums) {
let obj = {};
let len = nums.length;
let judge = len/3;
let result = []
for(let i = 0; i<len; i++){
if(obj[ nums[i] ]) {
// if( count > judge)
if(obj[ nums[i] ] + 1 > judge){
result.push( nums[i] )
}else {
obj[ nums[i] ] ++;
}
}else {
obj[ nums[i] ] = 1;
}
}
return [...result];
};
var majorityElement = function(nums) {
let obj = {};
let len = nums.length;
let judge = len/3;
let result = new Set();
for(let i = 0; i<len; i++){
if(obj[ nums[i] ]) {
if(obj[ nums[i] ] + 1 > judge){
// add Here
result.add( nums[i] )
}else {
obj[ nums[i] ] ++;
}
}else {
obj[ nums[i] ] = 1;
// add Here
if(obj[ nums[i] ] > judge){
result.add( nums[i] )
}
}
}
return [...result];
};
if(obj[ nums[i] ]) {
obj[ nums[i] ] ++;
}else {
obj[ nums[i] ] = 1;
}
// --可以用以下取代----------
(nums[i] in obj) ? obj[ nums[i] ] ++ : obj[ nums[i] ] = 1;
var majorityElement = function(nums) {
let obj = {};
let len = nums.length;
let judge = len/3;
let result = [];
for(let i = 0; i<len; i++){
(nums[i] in obj) ? obj[ nums[i] ] ++ : obj[ nums[i] ] = 1;
}
Object.keys(obj).forEach( key => {
if(obj[key] > judge) result.push(key)
})
return result;
};