king-lxt / LeetCode-javasctipt

leetCode 答案
0 stars 0 forks source link

多数元素 #8

Open king-lxt opened 3 years ago

king-lxt commented 3 years ago

给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在多数元素。 示例 1:

输入:[3,2,3] 输出:3 示例 2:

输入:[2,2,1,1,1,2,2] 输出:2

king-lxt commented 3 years ago
var majorityElement = function(nums) {
    const map = new Map();
    for(let i = 0; i < nums.length; i++){
        if(map.has(nums[i])){
            const num = map.get(nums[i]);
            map.set(nums[i],num+1);
        }else{
            map.set(nums[i],1);
        }
    }

    console.log(map)

    for(const [key,val] of map){
        if(val > nums.length/2) return key;
    }
};
king-lxt commented 3 years ago

先排序,在比较

var majorityElement = function(nums) {
    const n = nums.length;
    const sort = nums.sort((a, b) => a - b);

    return sort[Math.floor(n / 2)]
};