博客
关于我
微软高频面试模拟题: 数组中第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/

你可能感兴趣的文章
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>
No static resource favicon.ico.
查看>>
no such file or directory AndroidManifest.xml
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>
NO.23 ZenTaoPHP目录结构
查看>>
no1
查看>>
NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
查看>>
NOAA(美国海洋和大气管理局)气象数据获取与POI点数据获取
查看>>
NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
查看>>
node
查看>>
node exporter完整版
查看>>
node HelloWorld入门篇
查看>>
Node JS: < 一> 初识Node JS
查看>>
Node JS: < 二> Node JS例子解析
查看>>
Node Sass does not yet support your current environment: Linux 64-bit with Unsupported runtime(93)解决
查看>>
Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime(72)
查看>>
Node 裁切图片的方法
查看>>
node+express+mysql 实现登陆注册
查看>>
Node+Express连接mysql实现增删改查
查看>>