Find M Smallest Elements
EasyPractice library · +10 XPheapspriority queues
Given a list of N integers and an integer M, find the M smallest elements in the list. Print these M elements in non-decreasing order.
Input
The first line contains two integers N and M, separated by a space. The second line contains N integers, the elements of the list.
Output
Print the M smallest integers, separated by spaces, in non-decreasing order.
Constraints
1 <= M <= N <= 1000. All integers in the list are between -10^9 and 10^9.
Time limit 1 s (native code; slower languages get more)Memory 256 MB13 hidden tests
Example 1
Input
5 3 4 1 5 2 3
Output
1 2 3
The 3 smallest elements are 1, 2, 3.
Example 2
Input
7 2 10 20 5 15 30 25 35
Output
5 10
The 2 smallest elements are 5, 10.
Hints
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
Example 1 input
5 3 4 1 5 2 3
Example 2 input
7 2 10 20 5 15 30 25 35