题目:
Given an array of size n, find the majority element. The majority element is the element that appears more than b n 2 c times.You may assume that the array is non-empty and the majority element always exist in the array.
INPUT:
Line 1: the length of array.
Line 2: the all elements in array and split by spaces
OUTPUT:
Line 1: A single integer that is the majority element.
代码:
#include<iostream>
#include<vector>
using namespace std;
int findMajority(vector<int>& nums,int start,int end) {
if (start >= end)return nums[end];
int mid = start + (end - start) / 2;
int m1 = findMajority(nums,start, mid);
int m2 = findMajority(nums,mid + 1,end);
int count = 0;
for (int i = start; i <= end; i++) {
if (nums[i] == m1)count++;
}
if (count > (end - start + 1) / 2)return m1;
return m2;
}
int main() {
int n;
cin >> n;
vector<int> nums;
for (int i = 0; i < n; i++) {
int t;
cin >> t;
nums.push_back(t);
}
int res = findMajority(nums, 0, n - 1);
cout << res;
int c;
cin >> c;
return 0;
}