摩尔投票法
摩尔投票法
摩尔投票法用于求取数组中出现超过一半的数字。
空间复杂度: O(1)
时间复杂度: O(n)
摩尔投票算法的基本思想很简单,它通过消除不同元素之间的对抗来找到可能的多数元素。算法遍历数组并维护两个变量:候选元素(candidate)和其对应的票数(count)。开始时,候选元素为空,票数为0。然后对于数组中的每个元素(current_num),执行以下步骤
- 如果当前数current_num == count ,则将该数设为candidate,同时count++;
- 2.如果candidate == current_num, 则count++;反之,则count--
- 3.当count减到0时,candidate再更新数据
如果数组中存在一个数出现次数大于数组长度的1/2,则最后的candidate一定为该数.
copy int findMajorityElement(vector<int> nums) { int candidate, count = 0; for(const auto& current_num : nums){ if(count == 0){ candidate = current_num; } if(current_num == candidate){ ++count; }else{ --count; } } //检查candidate是否是出现次数超过一半的数 //因为有可能数组中不存在超过一半的数 int candidate_count = 0; for(const auto& n : nums){ if(n == candidate){ ++candidate_count; } } if(candidate_count > nums.size() / 2){ return candidate; }else{ // 不存在超过一半的数 return -1; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步