Skip to content

Commit 568b383

Browse files
committed
majorityElement
1 parent 215e67d commit 568b383

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

majorityElement.cpp

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#include<vector>
2+
using namespace std;
3+
4+
class Solution {
5+
public:
6+
int calElementCount(const vector<int>& nums, int element){
7+
int res = 0;
8+
for(int e : nums){
9+
if(e == element)
10+
res++;
11+
}
12+
return res;
13+
}
14+
int majorityElement(vector<int>& nums) {
15+
int majorityCount = nums.size() / 2;
16+
17+
while (true)
18+
{
19+
int index = rand() % nums.size();
20+
if(calElementCount(nums, nums[index]) > majorityCount)
21+
return nums[index];
22+
}
23+
24+
}
25+
};

0 commit comments

Comments
 (0)