Problem description: Find the maximum N number in the n-length sequence.
1. Bubble Sorting
You can put the maximum number of bubbles at the end of the sequence and bubble the sequence n times.
Time Complexity: O (N * n)
Space complexity: O (1)
2. Scan the array and store the N largest number in the cache. When there is a larger number, replace the number in the cache.
Top_n (A, n) n = length of a create array T [N] = {-∞} t = 0 for I = 0, n-1 do if T [N-1] <A [I] Then insert a [I] To sorted array T []
Time Complexity: O (N * n)
Space complexity: O (N)
You can use the minimum heap instead of the maximum N number of cached array storage. In this way, when a [I] is greater than the heap top element, use a [I] instead of the heap top element, and then adjust the heap, complexity: O (N * lgn)
3. Heap sorting and priority queue
Construct a heap and extract n elements from the top of the heap
Time Complexity: O (N + N * lgn)
Space complexity: O (1)