LeetCode——面试题 17.10. 主要元素(摩尔投票法)

面试题 17.10. 主要元素

数组中占比超过一半的元素称之为主要元素。给定一个整数数组,找到它的主要元素。若没有,返回-1。

示例 1:

输入:[1,2,5,9,5,9,5,5,5]
输出:5

示例 2:

输入:[3,2]
输出:-1


示例 3:

输入:[2,2,1,1,1,2,2]
输出:2

说明:
你有办法在时间复杂度为 O(N),空间复杂度为 O(1) 内完成吗?

思路

利用摩尔投票法进行解决:
摩尔投票法默认数组中存在出现次数大于数组长度一般的元素,摩尔投票法就是找出这个元素,其具体做法是:

  • 定义一个元素变量(temp = 0)和一个计数器(count = 0)
  • 开始遍历计算投票,如果nums[i] = temp 那么count++ 否则count--
  • 当count 为0 的时候,将下一个元素作为temp,循环操作,count = 0;
  • 循环结束时,当前元素即为目标元素

此题中,如果数组中不存在主元素,则需要验证一下。

code

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        // 摩尔投票算法
        int temp, count = 0;
        for(int x : nums)
        {
            if(count == 0)
            {
                temp = x;
                count++;
            }
            else
            {
                if(temp == x)
                    count++;
                else
                    count--;
            }
        }

        if(count > 0)
        {
            int t = 0;
            for(int x : nums)
                if(x == temp)
                    t++;
            if(t > nums.size()/2) return temp;
        }

        return -1;
        
    }
};

链接

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-majority-element-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

原文地址:https://www.cnblogs.com/jiashun/p/LeetCode_1710.html