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

169. 多数元素 #28

Open
zpc7 opened this issue Aug 7, 2022 · 0 comments
Open

169. 多数元素 #28

zpc7 opened this issue Aug 7, 2022 · 0 comments
Labels
简单 LeetCode 难度定级

Comments

@zpc7
Copy link
Owner

zpc7 commented Aug 7, 2022

169. 多数元素

/**
 * @param {number[]} nums
 * @return {number}
 */
 // 普通方法
var majorityElement = function (nums) {
    const map = {};
    let res;

    for (let i = 0; i < nums.length; i++) {
        map[nums[i]] = (map[nums[i]] || 0) + 1;
        if (map[nums[i]] > nums.length / 2) {
            res = nums[i]
        }
    }
    return res;
};
// 抵消法
const majorityElement = nums => {
    let count = 1; // 遍历从下标1的元素开始, 于是给count设置1
    let majority = nums[0]; // 初始值给第一个元素

    for (let i = 1; i < nums.length; i++) {
        // 如果次数被抵消完, 说明等于majority和不等于majority的一样多
        if (count === 0) {
            majority = nums[i];
        }
        if (nums[i] === majority) {
            // 重复的就+1
            count++;
        } else {
            // 不重读就抵消count
            count--;
        }
    }
    return majority;
};
@zpc7 zpc7 added 简单 LeetCode 难度定级 JS and removed JS labels Aug 7, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
简单 LeetCode 难度定级
Projects
None yet
Development

No branches or pull requests

1 participant