多数投票算法
来源:互联网 发布:mac os x 13.1.02 编辑:程序博客网 时间:2024/06/05 09:08
**多数投票算法**在一个数组中,元素个数为n,获得元素出现次数大于n/2的数,如果有满足条件的数,输出该数;没有满足条件的数,输出-1。(使用lua实现该算法)**普通思路:**1:遍历该数组,将数组中出现的每个数保存在table表count中2:设置result为-1表示需要返回的数,遍历count,将出现的次数和n/2比较,大于的话,则将值复制给result3:返回result,即为结果**代码如下:**local test = {6,2,5,8,4,11,2,3,5,9,5,5,5,5,5,}function majorityElement( data ) local count = {} for i, v in pairs(data) do count[v] = (count[v] or 0) + 1 end local max = #data local result = -1 for i, v in pairs(count) do if (v * 2) > max then result = i break end end return resultendprint("the result is : ", majorityElement(test))**运行结果如下:**the result is : -1**算法思路:**1:一个变量result表示所求的元素,cout表示统计的个数,将count初始位02:第一遍遍历,找到可能满足条件的元素,并复制给result1):遍历data,如果count == 0,则将数值赋予result,count设为12):如果count不为0,遍历的值和result相同,则count加1,否则count减13:第二遍遍历,将count设为0,如果遍历的值和result相同,则count加1,否则count减14:如果count <= 0的话,说明没有满足条件的元素,返回-1,否则返回result。**代码如下:**local test = {6,2,5,8,4,11,2,3,5,9,5,5,5,5,5,}function majorityElement_2( data ) local result = -1 local count = 0 for i, v in pairs(data) do if count == 0 then result = v count = 1 else count = (v == result) and (count + 1) or (count - 1) end end count = 0 for i, v in pairs(data) do count = (v == result) and (count + 1) or (count - 1) end return count <= 0 and -1 or resultendprint("the result is : ", majorityElement_2(test))**运行结果如下:**the result is : -1
0 0
- 多数投票算法
- 多数投票算法
- 多数投票算法
- 多数投票算法 Majority Vote Algorithm
- 多数投票算法(Majority Vote Algorithm)
- LeetCode--Majority Element II & 多数投票算法
- 多数投票算法 Majority Vote Algorithm
- LeetCode--Majority Element II & 多数投票算法
- 多数投票算法(Boyer-Moore Algorithm)详解
- Majority Vote Alogrithm 多数投票算法
- 多数投票算法 Majority Vote Algorithm
- 【LeetCode】169. Majority Element (多数投票算法 & 算法迁移能力)
- 多数投票算法 --- A linear time majority vote algorithm
- Boyer–Moore majority vote algorithm 博耶-穆尔多数投票算法 leetcode第229题
- leetCode_Majority Element II【多数投票法】
- 投票排名算法
- 用户投票算法
- 寻找多数元素 算法
- HTTPS原理
- java 导出导入备份redis数据库
- koa2 初探
- 遍历List集合的三种方法
- POJ 2891 Strange Way to Express Integers(扩展欧几里得)
- 多数投票算法
- 【机器学习PAI实践四】如何实现金融风控
- Cocos2d-x3.2 双击事件
- vsftpd设置被动模式
- 如何进入到Docker容器内部
- typedef用法
- android xm
- 对STM32 NVIC的理解
- [RK3288][Android6.0] 调试笔记 --- 开机默认选择24小时制时间格式