java - 面试题:定义一个数组长度是49,在里边随机放入1到50中的49个,设计一种最快的算法,求出那个数没被放入。
伊谢尔伦
伊谢尔伦 2017-04-18 10:50:37
0
3
611

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

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(3)
黄舟

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

阿神

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.

黄舟

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template