42 lines
1.0 KiB
Python
42 lines
1.0 KiB
Python
import random
|
|
|
|
|
|
#
|
|
# You have a array with integers: e.g. [ 1, -2, 0, 6, 2, -4, 6, 6 ]
|
|
# You need to write a function which will evenly return indexes of a
|
|
# max value in the array.
|
|
# In the example above max value is 6, and its positions are 3, 6 and 7.
|
|
# So each run function should return random index from the set.
|
|
#
|
|
# Try to implement with O(n) for computation and memory.
|
|
# Try to reduce memory complexity to O(1).
|
|
#
|
|
def return_max_evenly(arr):
|
|
mv = float('-inf')
|
|
mi = -1
|
|
mc = 0
|
|
for i in range(len(arr)):
|
|
if mv < arr[i]:
|
|
mv = arr[i]
|
|
mi = i
|
|
mc = 1
|
|
elif mv == arr[i]:
|
|
mc = mc + 1
|
|
if random.random() < 1./mc:
|
|
mi = i
|
|
if mi != -1:
|
|
return mi
|
|
|
|
|
|
if __name__ == "__main__":
|
|
random.seed()
|
|
arr = [1, -2, 0, 6, 2, -4, 6, 6]
|
|
ret = {}
|
|
for i in range(10000):
|
|
r = return_max_evenly(arr)
|
|
if r in ret:
|
|
ret[r] = ret[r] + 1
|
|
else:
|
|
ret[r] = 1
|
|
print(ret)
|