Majority Element
Last updated
Was this helpful?
Last updated
Was this helpful?
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, 其它看成-1, 总和会是正的。利用此思想每遇到和target相同的+1, 否则-1,当为负时就把当前换成target。任何一个不是解的target都会被冲为负,遇到解后会一直保持正数直到结束。
时间O(N), 空间O(1)