您的位置:首页 > 其它

LeetCode #229: Majority Element II

2016-09-22 11:20 309 查看

Problem Statement

(Source) Given an integer array of size n, find all elements that appear more than
⌊ n/3 ⌋
times. The algorithm should run in linear time and in
O(1)
space.

Solution

This problems can be solved using a modified version of the
Boyer–Moore majority vote algorithm
(wiki).

There could be at most 2 elements that appear more than
⌊ n/3 ⌋
times in an given array of size n. Hence the idea is to keep two possible candidates at the same time, and do a “appearance times check” to see if any of the possible candidates has appearance times more than
⌊ n/3 ⌋
after the main loop.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  主投票