多数投票算法

**多数投票算法**
在一个数组中,元素个数为n,获得元素出现次数大于n/2的数,如果有满足条件的数,输出该数;没有满足条件的数,输出-1。(使用lua实现该算法)

**普通思路:**
1:遍历该数组,将数组中出现的每个数保存在table表count中
2:设置result为-1表示需要返回的数,遍历count,将出现的次数和n/2比较,大于的话,则将值复制给result
3:返回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 result
end
print("the result is : ", majorityElement(test))

**运行结果如下:**
the result is : -1

**算法思路:**
1:一个变量result表示所求的元素,cout表示统计的个数,将count初始位0
2:第一遍遍历,找到可能满足条件的元素,并复制给result
1):遍历data,如果count == 0,则将数值赋予result,count设为1
2):如果count不为0,遍历的值和result相同,则count加1,否则count减1
3:第二遍遍历,将count设为0,如果遍历的值和result相同,则count加1,否则count减1
4:如果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 result
end

print("the result is : ", majorityElement_2(test))

**运行结果如下:**
the result is : -1
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章