-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path169.多数元素.cpp
37 lines (34 loc) · 916 Bytes
/
169.多数元素.cpp
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
#include <iostream>
#include <vector>
using namespace std;
/*
* @lc app=leetcode.cn id=169 lang=cpp
*
* [169] 求众数
*/
// @lc code=start
class Solution {
public:
int majorityElement(vector<int>& nums) {
return dfs(nums, 0, nums.size() - 1);
}
int dfs(const vector<int>& nums, const int start, const int end) {
if (start == end) return nums.at(start);
int mid = start + (end - start) / 2;
int left = dfs(nums, start, mid);
int right = dfs(nums, mid + 1, end);
if (left == right) return left;
int leftCount = countNum(nums, left, start, end);
int rightCount = countNum(nums, right, start, end);
return leftCount > rightCount ? left : right;
}
private:
int countNum(const vector<int>& nums, int n, int start, int end) {
int count = 0;
for (int i = start; i <= end; ++i) {
if (nums[i] == n) count++;
}
return count;
}
};
// @lc code=end