Leetcode 169 & 229
169 Majority Element
Description
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.
题意:从一堆元素里面找出出现次数超过⌊ n/2 ⌋ 次的(最多)元素,做法很简单,可以用stl的count或者哈希表求出,也可以用分治法(比较困难),然后有种摩尔投票算法的比较好理解,大致做法就是用一个count初始化为0,然后遇到遍历数组元素第一个元素为1,同时把数组中这个元素赋值给majority,第二个元素与majority比较,相等count++,否则count–,如果count为0就回到上一步继续把下一个元素作为majority,count=1,最后输出majority。放个wiki的链接:Boyer–Moore majority vote algorithm,注意这种算法原型是只能用于找出majority元素(出现次数大于n/2)
class Solution {
public:
int majorityElement(vector<int>& nums) {
int count = 0, major, size = nums.size();
for (int i = 0; i < size; i++) {
if (count == 0) {
major = nums[i];
count += 1;
} else
count += major == nums[i]? 1:-1;
}
return major;
}
};
229 Majority Element II
Description
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.
题意:和上一题类似,但是是找出n/3的次数的元素,就需要在摩尔投票的算法上稍作修改,加多几个判断条件就可以了
class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
int count1 = 0, count2 = 0, size = nums.size(), major1 = -1, major2 = -1;
vector<int> res;
for (int i = 0; i < size; i++) {
if (major1 == nums[i])
count1++;
else if (major2 == nums[i])
count2++;
else if (count1 == 0) {
major1 = nums[i];
count1 = 1;
} else if (count2 == 0) {
major2 = nums[i];
count2 = 1;
} else {
count1--;
count2--;
}
}
count1 = count2 = 0;
for (int i = 0; i < size; i++) {
if (major1 == nums[i])
count1++;
if (major2 == nums[i])
count2++;
}
if (count1 > size / 3)
res.push_back(major1);
if (count2 > size / 3)
res.push_back(major2);
return res;
}
};