Topic:
Given An array of size N , find the majority element. The majority element is the element, the appears more than Times ⌊ n/2 ⌋ .
Assume that the array was non-empty and the majority element always exist in the array.
Solution: runtime:229 ms
public class Solution { //Learn online method, each find two different, then in pairs Delete, the last remaining is the element public int majorityelement (int[] num) { int Count = 0; int maj = 0; for (int i = 0; i < num.length; i++) { if (count = = 0) { maj = Num[i]; count++; } else{ if (maj = = Num[i]) { count + +; if (Count > Num.length/2) return maj; } else{ Count--;}} } Return maj;} }
Summary: This method is what I see from the Internet, but also most people's practice, just started to do not think of this method, but also want to use the array to do, but that is too complex. This method is worth learning.
Leetcode 169.Majority Element