O(n)的算法,找到失踪的整数

编程入门 行业动态 更新时间:2024-10-24 05:15:53
本文介绍了O(n)的算法,找到失踪的整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是数组A有n-1独特的整数的范围是[0,N-1],也就是说,有在此范围内,是不是在A.设计一个O(n)的算法发现,排名第一的数。只允许使用O(1)额外的空间除了数组A本身。

需要一些帮助这个问题,

解决方案
  • 总和的阵列。
  • 在使用等差数列公式计算预期的总和
  • 根据这些数值:一个是 0 + 1 + 2 + ... + N-1 ,另一种是你的实际元素的总和 - 认为他们之间的区别彼此有什么做一件有其他没有。确保你知道,答案是微不足道的。

    编辑:(理论评论): 请注意,和(阵列)需要 2 * log_2(MAX(ARR))位。所以,如果你的元素都是32位整数,你将需要至少64位重新present的总和。 出租车从纯理论的方法 - 它不是 O(1)。但是,您可以使用数组本身(它包含更多的则 2 * log_2(MAX(ARR))位)来存储的总和。

    An array A contains n-1 unique integers in the range [0, n-1], that is, there is one number from this range that is not in A. Design an O(n) algorithm for finding that number. Allowed to use only O(1) additional space besides the array A itself.

    need some help for this question,

    解决方案

  • Sum the array.
  • Calculate the expected sum using arithmetic progression formula
  • Given these values: one is 0 + 1 + 2 + ... + n-1, the other is the sum of your actual elements - think how they differ from each other, what does one have that the other does not. Make sure you know it, and the answer is trivial.

    EDIT: (Theoretical comment): Note that sum(array) needs 2*log_2(max(arr)) bits. So, if your elements are all 32 bits integers, you are going to need at most 64 bits to represent the sum. From purely theoretical approach - it is NOT O(1). However, you can use the array itself (It contains more then 2*log_2(max(arr)) bits) to store the sum.

    更多推荐

    O(n)的算法,找到失踪的整数

    本文发布于:2023-11-30 02:56:10,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1648485.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:整数   算法

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!