by Utkarsh Jaiswal
Technology
March 9, 2024
|
6 min read
Given an array nums
of size n
, return the majority element.
The majority element is the element that appears more than ?n / 2?
times. You may assume that the majority element always exists in the array.
Example 1:
Input: nums = [3,2,3] Output: 3
Example 2:
Input: nums = [2,2,1,1,1,2,2] Output: 2
Using the brute force approach, we first declare an object to store the frequency of each element. After saving the frequencies, we find the element with the largest count.
const obj = {} nums.forEach(x => { if(obj.hasOwnProperty(x)){ obj[x] = obj[x] + 1 }else{ obj[x] = 1 } }) const largetValue = Math.max(...Object.values(obj)) return Object.keys(obj).find(x => obj[x] === largetValue)
First, we sort the array, and since we know there will be more than n/2 elements, after sorting, we return the element at index n/2. This is because there will be more than n/2 elements.
nums.sort() return nums[Math.floor(nums.length/2)]