169. Majority Element

Description

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.

Constraints

Approach

Examples

Input: [3, 2, 3]

Output: 3

Solutions

/**
 * Time complexity : O(n^2). The brute force algorithm contains two 
 *    nested for loops that each run for nn iterations, adding up to 
 *    quadratic time complexity.
 * Space complexity : O(1). The brute force solution does not allocate 
 *    additional space proportional to the input size.
 */

class Solution {
    public int majorityElement(int[] nums) {
        int majorityCount = nums.length/2;

        for (int num : nums) {
            int count = 0;
            for (int elem : nums) {
                if (elem == num) {
                    count += 1;
                }
            }

            if (count > majorityCount) {
                return num;
            }

        }

        return -1;    
    }
}

Follow up

Last updated

Was this helpful?