Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the majority element in array

The majority element is the element that occurs more than half of the size of the array.

How to find the majority element in an array in O(n)?

Example input:

{2,1,2,3,4,2,1,2,2} 

Expected output:

2 
like image 718
Ali Tarhini Avatar asked Dec 01 '10 14:12

Ali Tarhini


People also ask

How do you find the majority of an element in an array?

A basic approach would be to check whether each element is the majority element or not. We can use two nested loops where the outer loop iterate over the array, and the inner loop counts the occurrences of each element. If we found an element with a frequency greater than n/2, that's our majority element.

How do you find the majority element in an array in CPP?

Majority Element in C++One element is said to be the majority element when it appears n/2 times in the array. Suppose an array is like {1, 2, 3, 3, 3, 3, 6}, x = 3, here the answer is true as 3 is the majority element of the array. There are four 3s. The size of the array is 7, so we can see 4 > 7/2.


1 Answers

// returns -1 if there is no element that is the majority element, otherwise that element  // funda :: if there is a majority element in an array, say x, then it is okay to discard  // a part of that array that has no majority element, the remaining array will still have // x as the majority element  // worst case complexity :  O(n)  int findMajorityElement(int* arr, int size) {      int count = 0, i, majorityElement;     for (i = 0; i < size; i++) {         if (count == 0)             majorityElement = arr[i];         if (arr[i] == majorityElement)              count++;         else             count--;     }     count = 0;     for (i = 0; i < size; i++)         if (arr[i] == majorityElement)             count++;     if (count > size/2)         return majorityElement;     return -1; } 
like image 166
Hitesh Gupta Avatar answered Sep 20 '22 08:09

Hitesh Gupta