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.

Example 1:

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

Example 2:

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

题意:

找到数组中元素出现频次超过n/2个的元素返回。第一个想法是排序,然后取中间坐标的元素返回即可。时间复杂度是O(nlogn)。排名


代码:

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

第二个思路是使用hashmap,对出现的元素进行统计,最后扫描一遍hashmap,对超过半数的元素进行返回。坏处是要消耗额外的存储空间。


第三个思路是扫描数组,复杂度为O(n),代码如下。这个思路主要是参考解题区的高赞答案。

int majorityElement(vector<int>& nums) {
        int count = 0, major;
        for(int i = 0; i<nums.size(); i++)
        {
            if(!count)
            {
                major = nums[i];
                count++;
            }
            else if(major != nums[i])
                count--;
            else
                count++;
        }
        return major;
    }


以上~











猜你喜欢

转载自blog.csdn.net/iLOVEJohnny/article/details/80517052