All problems

Problem 27

Majority Element

Easy · 10 pts · Array, Hash Table

Problem

You are given an array of N integers. Find the majority element: the value that appears more than N / 2 times, that is, in more than half of all positions. Such an element is guaranteed to exist. Counting with a hash map works. The Boyer-Moore voting algorithm uses no extra memory: keep a candidate and a counter, increase the counter when you see the candidate, decrease it otherwise, and pick a new candidate whenever the counter is 0. The majority element always survives.

Input

First line: integer N. Second line: N space-separated integers.

Output

Print the majority element.

Constraints

1 <= N <= 100000; -1000000000 <= A[i] <= 1000000000

Example input

3
3 2 3

Example output

3

Explanation

In 3 2 3, the value 3 appears 2 times out of 3, which is more than 3 / 2 = 1.5, so 3 is the majority element.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Find the Duplicate Number Next: Best Time to Buy and Sell Stock