-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmajority_element.cpp
More file actions
81 lines (75 loc) · 1.79 KB
/
majority_element.cpp
File metadata and controls
81 lines (75 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// =====================================================================================
//
// Filename: majority_element.cpp
//
// Description: 169. Majority Element.
//
// Version: 1.0
// Created: 09/19/2019 08:39:09 PM
// Revision: none
// Compiler: g++
//
// Author: Zhu Xianfeng (), xianfeng.zhu@gmail.com
// Organization:
//
// =====================================================================================
#include <algorithm>
#include <unordered_map>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
// Sort
class Solution1 {
public:
int majorityElement(std::vector<int>& nums) {
std::sort(nums.begin(), nums.end());
return nums[nums.size() / 2];
}
};
// Hash table
class Solution2 {
public:
int majorityElement(std::vector<int>& nums) {
std::unordered_map<int, int> counts;
for (int n : nums) {
counts[n]++;
}
for (auto& c : counts) {
if (c.second > (nums.size() / 2)) {
return c.first;
}
}
return 0;
}
};
// Boyer–Moore majority vote
class Solution3 {
public:
int majorityElement(std::vector<int>& nums) {
int i = 0;
int m = 0;
for (auto x : nums) {
if (i == 0) {
m = x;
i = 1;
} else if (x == m) {
i++;
} else {
i--;
}
}
return m;
}
};
TEST(Solution, majorityElement) {
std::vector<std::pair<std::vector<int>, int>> cases = {
std::make_pair(std::vector<int>{3, 2, 3}, 3),
std::make_pair(std::vector<int>{2, 2, 1, 1, 1, 2, 2}, 2),
};
for (auto& c : cases) {
EXPECT_EQ(Solution1().majorityElement(c.first), c.second);
EXPECT_EQ(Solution2().majorityElement(c.first), c.second);
EXPECT_EQ(Solution3().majorityElement(c.first), c.second);
}
}