Leetcode#169. Majority Element(四种解法)

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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

题意:给你一个数组,找出数组里面出现次数>n/2 = 因为只输出一个元素等价于找出出现次数最多的元素

sort排序 + 一次遍历(每次比较前一个和后一个是否相同)

我的代码:

class Solution {
public:
    int majorityElement(vector& nums)
    {
        sort(nums.begin(),nums.end());   //先排序
        int res=nums[0],sum=1,max=-1;
        for(int i=1;i<=nums.size();i++)
        {
            if(nums[i]==nums[i-1]) //计数
                sum++;
            else//不相同或者是最后一个元素时
            {
                if(max
后来百度一些别人的做法:

方法一:先sort排序,因为主元素出现次数大于n/2次,则中间元素肯定为多数元素:

class Solution {
public:
    int majorityElement(vector& nums)
    {
        sort(nums.begin(),nums.end());   //先排序
        return nums[nums.size()/2];
    }
};

方法二:哈希表

用map存放数字里面的每一个元素的次数,次数超过n/2就停止。

class Solution {
public:
    int majorityElement(vector& nums)
    {
        maps;
        for(int i=0;inums.size()/2)
            {
                return nums[i];
            }
        }
    }
};

方法三:分治法:

分治解法: 
首先将序列均分成两半,分别找出每一半的主元素。如果两个主元素相等,则直接返回1个;否则遍历完整序列,返回出现次数多于一半的那个主元素。 
边界条件:序列只有一个元素时,直接返回该元素

class Solution {
public:
    int majorityElement(vector& nums)
    {
       if(nums.size()==1) return nums[0];
        
       vectorv1 (nums.begin(),nums.begin()+nums.size()/2);
       int n1 = majorityElement(v1);
        
       vectorv2(nums.begin()+nums.size()/2,nums.end());
       int n2 = majorityElement(v2);
        
       if( n1 == n2)
           return n1;
        else
        {
            int cnt=0;
            for(int i=0;inums.size()/2)
                    return n1;
            return n2;
        }  
    }
};





你可能感兴趣的:(【LeetCode】,LeetCode)