用ruby实现的算法,将一个数字加到表示为数组的数字上

吉姆

我需要有关基于红宝石的解决方案的建议,以解决Interviewbit上的问题。问题如下

Given a non-negative number represented as an array of digits,

add 1 to the number ( increment the number represented by the digits ).

The digits are stored such that the most significant digit is at the head of the list. There can be upto 10,000 digits in the input array.

Example:

If the vector has [1, 2, 3]

the returned vector should be [1, 2, 4]

as 123 + 1 = 124. 

我的第一个解决方案如下

 def plusOne(a)
        new_number = a.join.to_i + 1
        result = []
        while new_number > 0
            result.push new_number%10
            new_number /= 10
        end
        result.reverse
 end

该算法看似正确,通过了测试输入,但提交后给出了“超过时间限制”。我的第二个解决方案是提交成功,如下。

def plusOne(a)
      carry = 1
      start_index = a.size - 1
      temp_result = []
      ans = []

      for i in start_index.downto(0)
            sum = a[i] + carry
            carry = sum/10
            temp_result.push sum%10
      end
      temp_result.push carry

      start_index = temp_result.size - 1
      while start_index >= 0 and temp_result[start_index] == 0
          start_index -= 1
      end

      while start_index >= 0
          ans.push temp_result[start_index]
          start_index -= 1
      end
      ans
    end

我的第一个解决方案似乎是O(n),因为我们只是迭代数字中的数字。那么,有人可以告诉我为什么它会超过时间限制吗?

谢谢

安东
while new_number > 0
    result.push new_number%10
    new_number /= 10
end

尽管乍看之下似乎是这样O(n),但至少是这样Ω(n²)

由于Ruby中的大数字是作为二进制数字数组(以2³²为基数的数字)存储和处理的,因此除法10是一项昂贵的操作。确切的时间复杂度取决于Ruby使用的除法算法,但是new_number /= 10必须处理所有new_number的二进制数字,因此它的速度不能快于O(n)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

将一个数字加到存储在数字数组中的数字

将一个数字加到一个数组中以完成一组数字

找出一个数字的总和(用c表示)

如何将数组的最后一个元素设置为某个数字?

C#将数组中的上一个数字添加到下一个

将数字分割成一个数组

如何使脚本每秒将一个数字加到一个值上?(卢阿)

将一个数字分成相等的值并推送到一个数组

给定数字N和数组A。检查N是否可以表示为一个或多个数组元素的乘积

我在reactjs中有一个秒表,如何将每个数字添加到某种数组中以显示每个数字?

当第一个数字为负数时,Kadane的算法无法满足条件

从数字数组中获取一个数字

将整数数组中的数字连接成Golang中的一个数字?

用另一个数组中的数字顺序制作一个数组

将数字推入一个数组,然后将该数组推入另一个数组-JavaScript

算法:分解一个数字 Douts

一个输出N个数字最大的算法?

将数字的标志放到另一个数字上?

确定一个数字是否由其他两个数字相乘的算法

一个数字的数字总和

算法:给定一个数字数组A,创建一个数组B,其中B [i] = sum(A [j]:A [j] <= A [i])

为数组的每个项目增加和减少一个数字

mysql_fetch_array返回一个数组,数字为“ 1”

为数组中的每个元素添加一个数字[Double]

将一个数组中的数字与另一个数组中的数字进行比较并返回结果

如何将一个数组中的一组数字相加?

将一串数字拆分成一个数组

将下一个数字添加到R中向量中的前一个数字,For循环

检查一个数字是否可以表示为 2 的 x 次幂之和?