dongpeng0127 2018-04-06 15:14
浏览 133

时间复杂度:查找数组的模式

Being apart of a challange for beginners, I would like to know if my algorithm is indeed O(n) as I intended it to be.

The idea is simple, I'm given the task to create an algorithm that finds the mode of an integer array. The only catch was that if two integers in the array had the same multiplicity, the mode would be the lesser integer.

I've seen other algorithms around that do the job in O(n logn), however in the challange description it was mentioned that it could be done in O(n).

First of, I created a hash table that stores each integer that is found in the array with a key that represents it's own multiplicity.

If we have an element with the same multiplicity as the maximum multiplicity we check if the new element is less than mode. If it is, the new element becomes the new mode.

I chose Golang for my implementation.

func mode(input []int) (int, error) {

    // Error handeling.
    if len(input) == 0 {
        return -1, errors.New("can't find the mode of an empty array")
    }

    // Initilize a hashtable with key representing the multiplicities.
    m := make(map[int]int)

    mode := 0

    // The biggest multiplicity.
    max := 0

    for _, elem := range input {
        m[elem]++
        if m[elem] > max {
            max = m[elem]
            mode = elem
        }
        if m[elem] == max && mode > elem {
            mode = elem

        }
    }
    return mode, nil
}
  • 写回答

1条回答 默认 最新

  • doudizhi947129 2018-04-06 15:37
    关注

    More or less. The map insertions and lookups are somewhere between O(1) and O(log n), where n is the number of elements in the map, not in the input array. So your result will be close to O(n), or more accurately somewhere between O(n) and O(n log m) where m is the number of unique entries in the input.

    评论

报告相同问题?

悬赏问题

  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。
  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题