法一:Arrays.sort(nums);
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}
}
法二:HashMap
class Solution {
public int majorityElement(int[] nums) {
HashMap<Integer,Integer>mp=new HashMap();
for(int num:nums){
if(mp.containsKey(num))
mp.put(num,mp.get(num)+1);
else mp.put(num,1);
}
for(int key:mp.keySet()){
if(mp.get(key)>nums.length/2)
return key;
}
return -1;
}
}
法三:哈希表 c++
class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int,int>mp;
for(auto it:nums){
mp[it]++;
if(mp[it]>nums.size()/2) return it;
}
return 0;
}
};