169. 多数元素

解法1

多数元素重复次数大于一半,多数投票,最终ans至少多出现一次

class Solution {
    public int majorityElement(int[] nums) {
        int ans = nums[0], cnt = 1;
        for(int i = 1; i < nums.length; i++) {
            if (ans == nums[i]) {
                cnt++;
            } else {
                cnt--;
                if (cnt < 0) {
                    ans = nums[i];
                    cnt = 1;
                }
            }
        }
        return ans;
    }
}

相关推荐

  1. [leetcode] 169. 多数元素

    2024-05-26 01:36:35       54 阅读
  2. 169.多数元素

    2024-05-26 01:36:35       37 阅读
  3. leetcode 169.多数元素

    2024-05-26 01:36:35       199 阅读
  4. LeetCode 169. 多数元素

    2024-05-26 01:36:35       38 阅读
  5. 169. 多数元素

    2024-05-26 01:36:35       36 阅读
  6. leetcode-169-多数元素

    2024-05-26 01:36:35       31 阅读
  7. 【LeetCode】169. 多数元素

    2024-05-26 01:36:35       30 阅读
  8. 多数元素算法(leetcode第169题)

    2024-05-26 01:36:35       52 阅读
  9. LeetCode:169.多数元素(哈希表)

    2024-05-26 01:36:35       58 阅读

最近更新

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

    2024-05-26 01:36:35       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-26 01:36:35       100 阅读
  3. 在Django里面运行非项目文件

    2024-05-26 01:36:35       82 阅读
  4. Python语言-面向对象

    2024-05-26 01:36:35       91 阅读

热门阅读

  1. 15、Go Gin常见响应返回详解

    2024-05-26 01:36:35       37 阅读
  2. 掌握C++回调:按值捕获、按引用捕获与弱引用

    2024-05-26 01:36:35       35 阅读
  3. 【数据结构与算法 | 基础篇】数组模拟栈

    2024-05-26 01:36:35       36 阅读
  4. 银发经济:老龄化社会中的机遇与挑战

    2024-05-26 01:36:35       36 阅读
  5. 基于Amazon Cognito的安全登录与资源访问

    2024-05-26 01:36:35       28 阅读
  6. ORACLE 6节点组成的ACFS文件系统异常的分析思路

    2024-05-26 01:36:35       27 阅读
  7. Nginx 从入门到精通-Nginx-Web服务器的瑞士军刀

    2024-05-26 01:36:35       32 阅读
  8. PostgreSQL入门教程

    2024-05-26 01:36:35       29 阅读
  9. 系统分析师-案例分析-数据库

    2024-05-26 01:36:35       38 阅读
  10. 巧用count与count()

    2024-05-26 01:36:35       33 阅读