Skip to content

Commit 698a084

Browse files
Create Day 6 Majority Element.cpp
1 parent 28cba4e commit 698a084

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Day 6 Majority Element.cpp

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
PROBLEM:
2+
3+
4+
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
5+
6+
You may assume that the array is non-empty and the majority element always exist in the array.
7+
8+
Example 1:
9+
10+
Input: [3,2,3]
11+
Output: 3
12+
Example 2:
13+
14+
Input: [2,2,1,1,1,2,2]
15+
Output: 2
16+
17+
18+
19+
SOLUTION:
20+
21+
22+
class Solution {
23+
public:
24+
int majorityElement(vector<int>& nums) {
25+
26+
int i,n,k;
27+
n=nums.size();
28+
k=n/2;
29+
30+
unordered_map<int,int> m;
31+
32+
for(i=0;i<n;i++)
33+
{
34+
m[nums[i]]++;
35+
36+
if(m[nums[i]]>k)
37+
return nums[i];
38+
}
39+
40+
return -1;
41+
}
42+
};

0 commit comments

Comments
 (0)