Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

27、多数元素 #27

Open
conan1992 opened this issue May 9, 2020 · 0 comments
Open

27、多数元素 #27

conan1992 opened this issue May 9, 2020 · 0 comments
Labels

Comments

@conan1992
Copy link
Owner

题目

给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。

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

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

var majorityElement = function(nums) {
    var map = new Map();
    nums.forEach(function(item){
        var result = map.get(item) ? map.get(item)+1 : 1
        map.set(item, result)
    });
    var max = 0;
    var target;
    map.forEach(function(item, key){
        if(item>max){
            max = item;
            target = key
        }
    });
    return target
};

投票法

/**
 * @param {number[]} nums
 * @return {number}
 */
var majorityElement = function(nums) {
    var count=0;
    var result;
    for(var i=0;i<nums.length;i++){
        if(count==0){
            result = nums[i]
        }
        if(nums[i]===result){
            count++
        }else{
            count--
        }
    }
    return result
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant