Finding the first n largest elements in an array

后端 未结 8 439
不思量自难忘°
不思量自难忘° 2020-12-09 04:42

I have got an array containing unique elements. I need to find out the first n largest elements in the array in the least complexity possible. The solution that I could thin

8条回答
  •  抹茶落季
    2020-12-09 05:25

    I tried this as per @Alexandre C.

    This gets the top 10 items of a unbounded input. It breaks after it processed 20 items from the input.

    import random
    import time
    top_10_items = []
    cnt = 1
    while True:
        rand = random.randint(1,100)
        print(rand)
    
        time.sleep(1)
        if len(top_10_items) !=10:
            top_10_items.append(rand)
        else:
            m = min(top_10_items)
            if rand > m:
                top_10_items.append(rand)
                top_10_items.remove(m)
    
        print(top_10_items)
    
        cnt+=1
        if cnt==20:
            break
    

提交回复
热议问题