题目描述
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
解题思路
接上题,其实就是考partition函数,partition函数可以把整数分为两部分,我们只要获得partition函数返回值为k-1的时候即可,一开始我让返回值为k结果报浮点错误(%0),是因为如果取的k正好为数组大小,则我的partition函数的获取随机数会出现%0的情况。看了评论区后想明白k-1即可。
Code
class Solution {
public:
int Partition(vector<int> &input, int st, int ed) {
srand((unsigned)time(NULL));
int pos = rand() % (ed-st+1) + st;
swap(input[pos], input[st]);
int temp = input[st];
while(st < ed) {
while(st < ed && temp <= input[ed]) ed--;
input[st] = input[ed];
while(st < ed && temp >= input[st]) st++;
input[ed] = input[st];
}
input[st] = temp;
return st;
}
void QuickSort(vector<int> &input, int st, int ed) {
if(st < ed) {
int pos = Partition(input, st, ed);
QuickSort(input, st, pos-1);
QuickSort(input, pos+1, ed);
}
}
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
vector<int> result;
if(!input.size() || input.size() < k || k <= 0) {
return result;
}
int st = 0, ed = input.size()-1;
int pos = Partition(input, st, ed);
while(pos != k-1) {
if(pos > k-1) {
ed = pos -1;
} else {
st = pos + 1;
}
pos = Partition(input, st, ed);
}
for(int i = 0; i<k; i++) {
result.push_back(input[i]);
}
QuickSort(result, 0, k-1);
return result;
}
};
- java
import java.util.ArrayList;
public class Solution {
public void swap(int []input, int i, int j) {
int temp = input[i];
input[i] = input[j];
input[j] = temp;
}
public int Partition(int []input, int left, int right) {
int temp = (int)Math.random()*(right-left+1)+left;
swap(input, left, temp);
temp = input[left];
while(left < right) {
while(left < right && input[right] >= temp) right--;
input[left] = input[right];
while(left < right && input[left] <= temp) left++;
input[right] = input[left];
}
input[left] = temp;
return left;
}
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> result = new ArrayList<Integer>();
if(input.length == 0 || k < 1 || k > input.length) return result;
int left = 0, right = input.length-1, pos;
do{
pos = Partition(input, left, right);
if(pos > k-1) {
right = pos-1;
} else {
left = pos+1;
}
} while(pos != k-1);
for(int i = 0; i<k; i++) {
result.add(input[i]);
}
return result;
}
}
总结
浮点错误有可能是%0 || /0
发生了