【LeetCode-数组】查找大多数元素

题目来源于 LeetCode 上第 169 号(Majority Element)问题,题目难度为 Easy,AC率52.6%

题目地址:https://leetcode.com/problems/majority-element/

题目描述

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

给定一个数组,数组的长度为n,找出数组中出现次数超过一半的元素

You may assume that the array is non-empty and the majority element always exist in the array.

你可以假设数组不为空,且元素一定存在数组中

Example 1:
    Input: [3,2,3]
    Output: 3
    
Example 2:
    Input: [2,2,1,1,1,2,2]
    Output: 2
复制代码

题目解析

采用的是摩尔投票算法,关于什么是摩尔投票算法,可以参考知乎这篇文章,戳这里

  1. 定义两个变量major和count,major 表示出现次数最多的元素,count表示暂时无法删除的元素个数
  2. 假设数组第一个数为出现次数最多的元素,major = nums[0],count=1
  3. 如果后面的数字相等 count+1,不相等 count-1
  4. 如果count为0,修改major为当前数,并重置 count=1

算法效率如下:

代码实现

class Solution {
    public int majorityElement(int[] nums) {
        int major = nums[0];
        int count = 1;
        for (int i = 1; i < nums.length; i++) {
            if (count == 0) {
                count = 1;
                major = nums[i];
            } else if (major == nums[i]) {
                count++;
            } else {
                count--;
            }
        }
        return major;
    }
}
复制代码

相关文章

【LeetCode-栈】有效的括号

【LeetCode-链表】面试题-反转链表

【LeetCode-二叉树】二叉树前序遍历

【LeetCode-数组】数组式整数加法

猜你喜欢

转载自blog.csdn.net/weixin_34306676/article/details/91362028