Leetcode_Array -- 169. Majority Element [easy]

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的数组,找到数组中的 majority 元素,majority元素是在数组中出现次数大于 n/2 向下取整次的元素

你可以嘉定数组非空且 majority 元素总是存在

Example 1:

Input: [3,2,3]
Output: 3

Example 2:

Input: [2,2,1,1,1,2,2]
Output: 2

Solutions:

Python

(1)
'''
因为majority元素一定存在,那么只要将元素统计一下出现个数,然后按照统计的个数排序,第一个数一定是majority元素
'''
class Solution:
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        dict0 = {}
        for i in nums:
            dict0[i] = dict0.get(i,0)+1
        list0 = sorted(dict0.items(),key = lambda d:d[1],reverse = True)
        return list0[0][0]
(2)
'''
将元素进行排序,nums[len(nums)//2]一定是majority,因为majority元素超过了1/2数组长度,排序后数组中间的元素一定是majority
'''
class Solution:
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        length = len(nums)//2
        nums[:] = sorted(nums,reverse = True)
        return nums[length]
C++

(1)
class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int length = floor(nums.size()/2);
        sort(nums.begin(),nums.end());
        return nums[length];
    }
};

(2)
/*
首先用unordered_map对nums中的元素进行计数统计
然后创建一个pair<int,int>,用Map中出现次数元素对pair进行更新
pair中留存的是出现次数最大的元素和它的次数,由于majority一定存在
那么pair中存放的一定是majority元素
*/
class Solution {
public:
    int majorityElement(vector<int>& nums) {
        unordered_map<int,int> Map;
        pair<int,int> order = {0,0};
        for (int i : nums){
            Map[i] += 1;
        }
        for (pair<int,int>element : Map){
            if (element.second > order.second){
                order = element;
            }
        }
        return order.first;
        
    }
};

(3)
/*
这个是leetcode上最快的算法,他的思想是设置一个标志位x,用来记录nums中元素出现的次数
将nums中元素分为两部分,最少一半是majority元素,剩余的是其他元素,只有majority元素
可以保持x减不到0,即t在等于majority之后不会被更新掉,t = majority,返回t就可以了
*/
class Solution {
public:
  int majorityElement(vector<int>& nums) {
        int size = nums.size();
        if(size==1) return nums[0]; 
        int t  = nums[0];
        int x  = 1;
        for(int i=1;i<size;i++)
        {
            if(x==0)
            {
                t = nums[i];
            }
            if(t==nums[i])
             x++;
            else 
             x--;
        }
       return t; 
    }
};

 

C++中map按照values进行排序:

https://blog.csdn.net/theonegis/article/details/48549887

https://blog.csdn.net/qq_17550379/article/details/80959968

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值