题目描述:
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”。
solution3:参考leetcode上提供的解题思路——初始化众数majority的值为0,出现的次数为0;遍历整个数组,当前的nums[i]如果等于当前的众数则count++,majority等于当前的nums[i],否则count--。当然本题中题目说明众数的数目会大于n/2,是上述办法可行的前提。(以下代码已通过leetcode测试)
int majorityElement(vector<int>& nums) {
int length = nums.size();
int count = 0;
int majority = 0;
for (int i = 0; i < length; i++) {
if ((majority == nums[i]) || (count == 0)) {
count ++;
majority = nums[i];
} else {
count--;
}
}
return majority;
}