Leetcode 169. Majority Element

题目

链接:https://leetcode.com/problems/majority-element/

**Level: ** Easy

Discription:
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

代码

class Solution{
public:
    int arrayNesting(vector<int>& nums) {
       class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int ret[2]={0};
        for(auto n: nums)
        {
            if(n==ret[0])
                ret[1]++;
            else
            {
                if(ret[1]!=0)
                    ret[1]--;
                else
                {
                    ret[0]=n;
                    ret[1]++;
                }
            }  
        }
        return ret[0];
        
    }
};

思考

  • 算法时间复杂度为O(n),空间复杂度为O(1)。
  • 最直接的想法就是排序取中间值输出,但是这样的时间复杂度是O(nlogn)。为了让时间复杂度为O(n),我们只能遍历一遍数组,如果对每个元素都计数,空间复杂度就是O(n)了,所以我们采用抵消的形式,最后记录下来的数字就是我们需要输出的数字。
原文地址:https://www.cnblogs.com/zuotongbin/p/10228301.html