Given a list of elements, find the majority element, which appears more than half the time (> floor(len(lst) / 2.0)
).
You can assume that such an element exists.
For example, given [1, 2, 1, 1, 3, 4, 0]
, return 1.
Example:
Input: arr = {1, 2, 1, 1, 3, 4, 0}
Output: 1
Approach
C++
#include <bits/stdc++.h>using namespace std;int findMajorityElement(vector<int> &arr){sort(arr.begin(), arr.end());int n = arr.size();return arr[n / 2];}int main(){vector<int> arr = {1, 2, 1, 1, 3, 4, 0};cout << findMajorityElement(arr) << "\n";return 0;}
No comments:
Post a Comment