search

Home  >  Q&A  >  body text

java - 面试题:定义一个数组长度是49,在里边随机放入1到50中的49个,设计一种最快的算法,求出那个数没被放入。

面试题:定义一个数组长度是49,在里边随机放入1到50中的49个,设计一种最快的算法,求出那个数没被放入。

伊谢尔伦伊谢尔伦2802 days ago614

reply all(3)I'll reply

  • 黄舟

    黄舟2017-04-18 10:52:37

    Find the sum from 1 to 50, then traverse the array to sum and subtract, how to

    reply
    0
  • 阿神

    阿神2017-04-18 10:52:37

    Create another array with a length of 50, initialize all to 0, traverse the given array, set the new array subscript equal to the current value of the given array to 1, and finally output the new array subscript with a value of 0. That was my first reaction, to wait for a better solution.

    reply
    0
  • 黄舟

    黄舟2017-04-18 10:52:37

    Use the sum of 1 to 50 to subtract all the numbers in the array:

    # array is an array with length 49
    
    ans = 1275
    
    for i in range(49):
        ans -= array[i]
        
    # ans is the number we want to find

    Time Complexity: O(n)
    Space Complexity: O(1)


    Questions I answered: Python-QA

    reply
    0
  • Cancelreply