在求数据的前K小项或者找找中位数以及快速排序算法中都会用到partation找数据的合适位置,
从而减小时间效率,本小章节总结常见的处理算法。
一:求数组的第K大的数
第一种解法:基于partation的时间复杂度为o[n]的解法!
这里是一个收敛数列:1 + 1/2 +1/3 + .... = 2
#include<iostream>
//o[n]时间的算法,缺点会改变原数据 { int left=0; left=index+1; } return a[k-1]; int main() |
可以看到的是这里找到的是从小到大的第6个
第二种解法:相对更为合理,特别适合做大数据的处理,以空间换取时间的做法。
利用了最大堆处理
class Solution { public: vector<int> GetLeastNumbers_Solution(vector<int> input, int k) { int len=input.size(); vector<int> res; if(len<=0||k>len||k<=0) return res; for(int i=0;i<k;++i) { res.push_back(input[i]); } //vector<int> res(input.begin(),input.begin()+k); //建堆 make_heap(res.begin(),res.end()); for(int i=k;i<len;i++) { if(input[i]<res[0]) { //先pop,然后在容器中删除 pop_heap(res.begin(),res.end()); res.pop_back(); //先在容器中加入,再push res.push_back(input[i]); push_heap(res.begin(),res.end()); } } //使其从小到大输出 sort_heap(res.begin(),res.end()); return res; } }; |
数组中超过一半的数
这里是用 map实现了 hash计数
习惯了 map对象 insert的方式插入对上面的额插入方式比较不适用,但是这是完全可以的
可以对它稍加变形
基于partation的单向链表的快速排序算法!
//#include <iostream> void swap(int* a,int * b) node *mysort(node *head,node *end) int main() //swap( & b->val ,& c->val); |