最小的k个数
题目
输入整数数组 arr ,找出其中最小的 k 个数。例如,输入4、5、1、6、2、7、3、8这8个数字,则最小的4个数字是1、2、3、4。
0 <= k <= arr.length <= 10000
0 <= arr[i] <= 10000
-
思路1 partition:
如果基于数组的第k个数字来调整,则使得比第k个数字小的所有数字都位于数组的左边,比第k个数大的都在右边。
时间复杂度 O ( n l o g k ) O(nlogk) O(nlogk),特比适合处理海量数据。 -
思路2 堆排序:
时间复杂度 O ( n ) O(n) O(n),要求可以修改输入的数组。
此题值得多刷
C++ 思路一
class Solution {
public:
vector<int> getLeastNumbers(vector<int>& arr, int k) {
if(arr.size() == k)
return arr;
if(arr.size()<k || k<=0 || arr.size()==0)
return vector<int>();
int start = 0;
int end = arr.size()-1;
int index = partition(arr, start, end);
while(index != k-1) //针对k,while循环结束后k前面的即为所求
{
if(index>k-1)
{
end = index-1;
index = partition(arr, start, end);
}
else
{
start = index+1;
index = partition(arr, start, end);
}
}
return vector<int>(arr.begin(), arr.begin()+k);
}
private:
int partition(vector<int>&arr,int start,int end)
{
int temp=arr[start];
while(start<end){
while(start<end && arr[end]>=temp)
end--;
arr[start]=arr[end];
while(start<end && arr[start]<=temp)
start++;
arr[end]=arr[start];
}
arr[start]=temp;
return start;
}
};
python 思路一
class Solution:
def getLeastNumbers(self, arr: List[int], k: int) -> List[int]:
def partition(arr: List[int], start: int, end: int) -> int:
temp = arr[start]
while start<end:
while start<end and arr[end]>=temp:
end -= 1
arr[start] = arr[end]
while start<end and arr[start]<=temp:
start += 1
arr[end] = arr[start]
arr[start] = temp
return start
if len(arr)==k:
return arr;
if len(arr)<k or k<=0 or not len(arr):
return []
start = 0
end = len(arr)-1
index = partition(arr, start, end)
while index != k-1:
if index > k-1:
end = index-1
else:
start = index+1
index = partition(arr, start, end)
return arr[:k]