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.
Hint:
- How many majority elements could it possibly have?
未解思路:根据盒球模型,采用三分支法求解,注意这种思路是概率思路,需要将数组重复10倍,并随机排列
class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
vector<int> nums2;
while (nums.size() > 2 || nums2.size() > 2){
if (nums.size() > 2){
for (int i = 0; i < nums.size(); i += 3){
if (i + 1 == nums.size()){
if (nums[i] == nums[0] || nums[i] == nums[1])
nums2.push_back(nums[i]);
continue;
}
if (i + 2 == nums.size()){
if (nums[i] == nums[0] || nums[i] == nums[i+1])
nums2.push_back(nums[i]);
else if(nums[i+1] == nums[0])
nums2.push_back(nums[i+1]);
continue;
}
if (nums[i] == nums[i + 1] || nums[i] == nums[i + 2]){
nums2.push_back(nums[i]);
}
else if (nums[i + 1] == nums[i + 2]){
nums2.push_back(nums[i + 1]);
}
}
nums.clear();
}
else if (nums2.size() > 2){
for (int i = 0; i < nums2.size(); i += 3){
if (i + 1 == nums2.size()){
if (nums2[i] == nums2[0] || nums2[i]==nums2[1])
nums.push_back(nums2[i]);
continue;
}
if (i + 2 == nums2.size()){
if (nums2[i] == nums2[0] || nums2[i] == nums2[i+1])
nums.push_back(nums2[i]);
else if (nums[i+1] == nums2[0])
nums.push_back(nums2[i + 1]);
continue;
}
if (nums2[i] == nums2[i + 1] || nums2[i] == nums2[i + 2]){
nums.push_back(nums[i]);
}
else if (nums2[i + 1] == nums2[i + 2]){
nums.push_back(nums[i + 1]);
}
}
nums2.clear();
}
}
if (!nums.empty()){
switch ((int)(nums.size())){
case 1:
return nums;
case 2:
if (nums[0] == nums[1])
nums.erase(nums.begin() + 1);
return nums;
}
}
if (!nums2.empty()){
switch ((int)(nums2.size())){
case 1:
return nums2;
case 2:
if (nums2[0] == nums2[1])
nums2.erase(nums2.begin() + 1);
return nums2;
}
}
return nums2;
}
};
AC思路:排序,检测个数是否大于n/3.
class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
vector<int> result;
if (nums.size() < 2)
return nums;
if (nums.size() == 2){
if (nums[0] == nums[1])
nums.erase(nums.begin() + 1);
return nums;
}
sort(nums.begin(), nums.end());
int target = nums[0];
int count = 1;
for (int i = 1; i < nums.size(); i++){
if (nums[i] == target){
count++;
}
else{
if (count > nums.size() / 3){
result.push_back(target);
if (result.size() == 2)
return result;
}
target = nums[i];
count = 1;
}
}
if(count > nums.size()/3)
result.push_back(target);
return result;
}
};