博客
关于我
微软高频面试模拟题: 数组中第K大的元素:快速选择算法
阅读量:230 次
发布时间:2019-03-01

本文共 865 字,大约阅读时间需要 2 分钟。

说下思路:首先选第一个数作为pviot,然后通过一趟快排操作将他放到正确位置,如果此时他正好是距离右端点的第k个数,那么这个就是第k大的数,如果他距离右端点的记录大于k,则说明,要找的数在这个点右边,如果距离小于k,说明要去左边找k-(end-left+1)个数。

class Solution {public:    int findKthLargest(vector
& nums, int k) { int n = nums.size(); helper(nums,0,n-1,k); return nums[n-k]; } void helper(vector
& nums, int start, int end, int k){ if(start>=end) return; int key = nums[start], left = start, right = end; while(left
=key) right--; swap(nums[left],nums[right]); while(left
<=key) left++; swap(nums[left],nums[right]); } if(end-left+1==k) return; else if(end-left+1>k) helper(nums,left+1,end,k); else helper(nums,start,left-1,k-(end-left+1)); }};

这个算法的时间复杂度是O(n)的,为什么,因为这个递归的过程近似于只需要常数次操作,就能找到答案。所以时间复杂度是O(n)

转载地址:http://ojqv.baihongyu.com/

你可能感兴趣的文章
NMF(非负矩阵分解)
查看>>
nmon_x86_64_centos7工具如何使用
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.7 Parameters vs Hyperparameters
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named 'pandads'
查看>>