Q:
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.
A1:
1: public class Solution {
2: public int majorityElement(int[] num) {
3:
4: int major=num[0], count = 1;
5: for(int i=1; i
6: if(count==0){
7: count++;
8: major=num[i];
9: }else if(major==num[i]){
10: count++;
11: }else count--;
12:
13: }
14: return major;
15: }
16: }
A2:
1: public class Solution {
2: public int majorityElement(int[] num) {
3: Arrays.sort(num);
4: return num[num.length / 2];
5: }
6: }