Time limit: 1 second
Space limit: 32768K
Heat index: 214405
Algorithm knowledge video explanation
Topic description
Enter n integers and find the smallest K number among them. For example, if you enter 8 numbers 4,5,1,6,2,7,3,8, the smallest 4 numbers are 1,2,3,4,.
C++ implementation:
class Solution { public: vector<int> GetLeastNumbers_Solution(vector<int> input, int k) { int t = input.size(); int x = 0; for(int i = 0; i < t - 1; i ++) { for(int j = 0; j < t - i - 1; j ++) { if(input[j] > input[j + 1]) { x = input[j]; input[j] = input[j + 1]; input[j + 1] = x; } } } vector <int> r; if(k > t) return r; else { for(int i = 0; i < k; i ++) { r.push_back(input[i]); } return r; } } };
python implementation:
# -*- coding:utf-8 -*- class Solution: def GetLeastNumbers_Solution(self, tinput, k): # write code here a = sorted(tinput) b = [] if k > len(tinput): return b else: b = a[0:k] return b