Implementation of Top N Problems

Source: Internet
Author: User

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)

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.