LeetCode:Majority Element Ⅱ

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.

解法一:

 1 class Solution {
 2 public:
 3     vector<int> majorityElement(vector<int>& nums) {
 4         unordered_map<int,int> mapping;
 5         unordered_map<int,bool> flag;
 6         vector<int> result;
 7         int minct=nums.size()/3;
 8         
 9         for(int i=0;i<nums.size();i++)
10         {
11             mapping[nums[i]]++;
12         }
13          
14         for(int i=0;i<nums.size();i++)
15         {
16             if(mapping[nums[i]]>minct)
17                 {   
18                     if(mapping[nums[i]])
19                     {
20                     result.push_back(nums[i]);
21                     mapping[nums[i]]=false;
22                     }
23                 }
24         }
25         return result;
26         
27     }
28 };
原文地址:https://www.cnblogs.com/xiaoying1245970347/p/4732003.html