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.
解法1:抵消的思路,O(N) Time + O(1) Space
运用抵消的思路,如果有多余半数的一个数字,那么如果我们俩俩抵消不一样的数字,最后剩下来的一定是最多的那个数字。
抵消的实现用一个计数器,当两个数字不一样的时候,计数器减少1,如果归0了则更改被选答案到当前选定的数字。
C++
Java
解法2:排序 O(NlogN)
因为多数元素个数超过半数,那么排序之后,当中的元素一定是最多的元素。
这个方法也能过OA
C++