**Description**Hints**Submissions**Solutions

Total Accepted: 192332 Total Submissions: 417285 Difficulty: Easy Contributor: LeetCode

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. **Credits:**Special thanks to @ts for adding this problem and creating all test cases.

Hide Company Tags  Adobe Zenefits Hide Tags  Array Divide and Conquer Bit Manipulation Hide Similar Problems  (M) Majority Element II

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class Solution {
    // O(n) time O(1) space fastest solution
    public int majorityElement(int[] nums) {
        int major = nums[0], count = 1;
        for (int i = 1; i < nums.length; i++) {
            if (count == 0) {
                count++;
                major = nums[i];
            } else if (major == nums[i]) {
                count++;
            } else {
                count--;
            }
        }
        return major;
    }
    
    public int majorityElementFailed(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int n : nums) {
            set.add(n);
        }
        int max = -1;
        
        int[] countList = new int[nums.length];
        
        for (int k : set) {
           for (int i = 0; i < nums.length; i++) {
               if (nums[i] == k) countList[i]++;
           }
        }
        return max;
    }
}