day 4: 169-majority-element

This commit is contained in:
Kaushik Narayan R 2023-09-29 14:01:40 -07:00
parent 688a352dbe
commit ae9f1fe46f
3 changed files with 37 additions and 0 deletions

View File

@ -0,0 +1,11 @@
#include "soln.hpp"
#include <iostream>
int main()
{
vector<int> nums = {2, 2, 1, 1, 1, 2, 2};
int answer = 2;
Solution soln;
cout << "Majority element is correct? " << soln.test(nums, answer) << endl;
return 0;
}

View File

@ -0,0 +1,17 @@
#include "soln.hpp"
int Solution::majorityElement(vector<int> &nums)
{
map<int, int> counts;
for (auto &it : nums)
{
counts[it]++;
if (counts[it] > (nums.size() / 2))
return it;
}
return -1;
}
bool Solution::test(vector<int>& nums, int answer) {
return majorityElement(nums) == answer;
}

View File

@ -0,0 +1,9 @@
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int majorityElement(vector<int> &nums);
bool test(vector<int> &nums, int answer);
};