Dare2Solve
The majority element in an array of size n
is the element that appears more than ⌊n / 2⌋
times. Given that the majority element always exists, it is guaranteed to be the most frequent element in the array. This problem can be solved efficiently by using a frequency count or a more optimal algorithm like the Boyer-Moore Voting Algorithm.
Alternatively, the Boyer-Moore Voting Algorithm can be used for a more optimal approach:
count
and candidate
.count
is 0, set candidate
to the current element and count
to 1.candidate
, increment count
.count
.candidate
will be the majority element.candidate
.The time complexity is O(n), where n
is the length of the array. This is because we iterate through the array once.
The space complexity is O(1) for the Boyer-Moore Voting Algorithm since it only uses a few variables. The space complexity is O(n) if using a frequency dictionary.
class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int, int> frequency;
for (int num : nums) {
frequency[num]++;}
int majorityElement = nums[0];
int maxCount = frequency[nums[0]];
for (const auto& pair : frequency) {
if (pair.second > maxCount) {
majorityElement = pair.first;
maxCount = pair.second;
}
}
return majorityElement;
}
};
class Solution(object):
def majorityElement(self, nums):
frequency = {}
for num in nums:
if num in frequency:
frequency[num] += 1
else:
frequency[num] = 1
majority_element = nums[0]
max_count = frequency[nums[0]]
for num, count in frequency.items():
if count > max_count:
majority_element = num
max_count = count
return majority_element
class Solution {
public void swap(int []arr,int i ,int j){
int temp =arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
public int majorityElement(int[] arr) {
for (int i = 1; i <arr.length ; i++) {
int j=i;
while(j >=1 && arr[j]<arr[j-1]){
swap(arr,j,j-1);
j--;
}
}
return arr[arr.length/2];
}
}
var majorityElement = function (nums) {
const f= {}
for(let num of nums){
if(f[num]) f[num]++
else f[num]=1
}
const fArr = Object.entries(f)
const ans = fArr.reduce((acc,curr)=>{
if(curr[1]> acc[1]) return curr
else return acc
})
return ans[0]
};