题目描述:
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
解题思路:solution1:统计出数组中每个元素出现的次数,出现次数最多的即为所求。一开始使用2重循环,不管元素重不重复都统计次数,去leetcode上检测“Time Limit Exceeded”。
solution2::用桶排序来统计元素次数,下面贴的代码,在本地编译器上测试没问题,去leetcode上检测“Runtime Error”。
#include<iostream>
#include<cmath>
#include<vector>
using namespace std;
int majorityElement(vector<int>& nums) {
int length = nums.size();
// calculate the count the majorityElement should appear
int number = 0;
if (length % 2) {
number = (length - 1) / 2;
} else {
number = length / 2;
}
int max = 0;
for (int i = 0; i < length; i++) {
// the element in the vector might be non-positive
if (abs(nums[i]) > max) {
max = abs(nums[i]);
}
}
int size1 = 2*max + 1;
int count[size1];
for (int i = 0; i < size1; i++) {
count[i] = 0;
}
for (int i = 0; i < length; i++) {
if (nums[i] < 0) {
count[size1 + nums[i]]++;
if (count[size1 + nums[i]] > number) {
return nums[i];
}
} else {
count[nums[i]]++;
if (count[nums[i]] > number) {
return nums[i];
}
}
}
// 把桶排的数组大小缩一半也没有用
/*
int size1 = max + 1;
int count[size1];
for (int i = 0; i < size1; i++) {
count[i] = 0;
}
int count1 = 0, max1;
int count2 = 0, max2;
for (int i = 0; i < length; i++) {
if (nums[i] > 0 || nums[i] == 0) {
count[nums[i]]++;
if (count[nums[i]] > count1) {
count1 = count[nums[i]];
max1 = nums[i];
if (count1 > number) {
return max1;
}
}
}
}
for (int i = 0; i < length; i++) {
if (nums[i] < 0) {
count[size1 + nums[i]]++;
if (count[size1 + nums[i]] > count2) {
count2 = count[size1 + nums[i]];
max2 = nums[i];
if (count2 > number) {
return max2;
}
}
}
}
*/
}
int main() {
int n, temp;
cin >> n;
vector<int> nums;
for (int i = 0; i < n; i++) {
cin >> temp;
nums.push_back(temp);
}
cout << majorityElement(nums);
return 0;
}
solution3:使用STL容器