【LeetCode 0169】【摩尔投票算法】主元素

  1. Majority Element

Given an array nums of size n, return the majority element.

The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.

Example 1:

**Input:** nums = [3,2,3]
**Output:** 3

Example 2:

**Input:** nums = [2,2,1,1,1,2,2]
**Output:** 2

Constraints:

  • n == nums.length
  • 1 <= n <= 5 * 10^4
  • -10^9 <= nums[i] <= 10^9

Follow-up: Could you solve the problem in linear time and in O(1) space?

Idea
Boyer Moore Vote Algorithm 
JavaScript Solution
/**
 * @param {number[]} nums
 * @return {number}
 */
var majorityElement = function(nums) {
    [res,count] = [nums[0],0]
    for(let n of nums){
        if(count == 0){
            [res,count] = [n,1]
        }else{
            if(res == n){
                count ++
            }else{
                count --
            }
        }
    }
    return res;
};
```

相关推荐

  1. LeetCode 0169】【投票算法元素

    2024-07-12 09:14:03       25 阅读
  2. 算法投票算法

    2024-07-12 09:14:03       55 阅读
  3. [LeetCode][LCR158]库存管理 II——投票

    2024-07-12 09:14:03       35 阅读
  4. 【数组】-Lc169-求众数(投票相抵消法)

    2024-07-12 09:14:03       53 阅读
  5. 多数元素算法(leetcode第169题)

    2024-07-12 09:14:03       50 阅读
  6. 固定区间存在重复元素算法(leetcode第219题)

    2024-07-12 09:14:03       59 阅读
  7. 【排序算法LeetCode-347. 前 K 个高频元素

    2024-07-12 09:14:03       47 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-12 09:14:03       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-12 09:14:03       71 阅读
  3. 在Django里面运行非项目文件

    2024-07-12 09:14:03       58 阅读
  4. Python语言-面向对象

    2024-07-12 09:14:03       69 阅读

热门阅读

  1. 每日一道算法题 LCR 151. 彩灯装饰记录 III

    2024-07-12 09:14:03       30 阅读
  2. 【随想】社交

    2024-07-12 09:14:03       23 阅读
  3. 谷歌独立站:纯净网络空间,自由与创新的融合

    2024-07-12 09:14:03       26 阅读
  4. Centos解决服务器时间不准的问题

    2024-07-12 09:14:03       23 阅读
  5. 计算机视觉发展历史、优势以及面临的挑战

    2024-07-12 09:14:03       19 阅读
  6. 使用bsdconfig配置CBSD NAT

    2024-07-12 09:14:03       24 阅读
  7. Oracle透明数据加密:数据泵文件导出

    2024-07-12 09:14:03       30 阅读