问题描述:

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

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

问题来源:Majority Element (详细地址:https://leetcode.com/problems/majority-element/description/)

思路:问题的意思浅显易懂,可以用好多方法解决,在这我介绍两种方法:

1.)我们利用hashmap来统计次数,直接次数超过一半的元素,我们就输出来;

2.)采用一种新的算法:Moore majority voting algorithm ,它的意思就是我们先假定第一个元素为最多的元素,并携带一个计数器count,赋一个初值,如果下一个元素等于它的话,计数器就加一,否则就减一,如果遇到计数器等于0了,我们就将当前这个数重新指定为新的主元素,并且计数器置为1,最后,如果这个元素是主元素,剩下来的必然是它。

代码:

第一种解法:

Leetcode之Majority Element 问题

第二种解法:

Leetcode之Majority Element 问题




相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-25
  • 2021-07-07
  • 2021-05-29
  • 2021-08-13
猜你喜欢
  • 2021-09-21
  • 2021-07-25
  • 2021-08-04
  • 2021-10-18
  • 2021-06-19
  • 2022-01-23
相关资源
相似解决方案