[leetcode]Kth Smallest Element in an Array
来源:互联网 发布:淘宝网连衣裙夏装 编辑:程序博客网 时间:2024/04/29 11:52
利用QuickSelect的思想进行递归查找
QuickSelect:https://en.wikipedia.org/wiki/Quickselect
主要思想是借鉴QuickSort的分割思路,不同的是,QuickSelect只从一边进行遍历,以最后一个元素为pivot,将原无序数组分割为两部分
The basic idea is to use Quick Select algorithm to partition the array with pivot:
Put numbers < pivot to pivot's leftPut numbers > pivot to pivot's right
Then
if indexOfPivot == k, return A[k]else if indexOfPivot < k, keep checking left part to pivotelse if indexOfPivot > k, keep checking right part to pivot
Time complexity = O(n)
利用QuickSelect查找第k大的数,同理可以查找第k小的数
public class Solution { public int findKthLargest(int[] nums, int k) { return findKthLargest(nums,0,nums.length-1,k-1); } public int findKthLargest(int[] nums,int start,int end,int k){ if(start>end){ return Integer.MAX_VALUE; } int left = start; int pivotValue = nums[end]; for(int i=start;i<end;i++){ if(nums[i]>pivotValue){ if(left!=i){ swap(nums,left,i); } left++; } } swap(nums,left,end); if(left==k){ return nums[left]; }else if(left<k){ return findKthLargest(nums,left+1,end,k); }else return findKthLargest(nums,start,left-1,k); } public void swap(int[] nums,int i,int j){ int temp=nums[i]; nums[i] = nums[j]; nums[j] = temp; }}
0 0
- [leetcode]Kth Smallest Element in an Array
- Leetcode Kth Largest Element in an Array
- Leetcode: Kth Largest Element in an Array
- LeetCode Kth Largest Element in an Array
- [LeetCode] Kth Largest Element in an Array
- [leetcode] Kth Largest Element in an Array
- leetcode--Kth Largest Element in an Array
- #leetcode#Kth Largest Element in an Array
- LeetCode Kth Largest Element in an Array
- 【Leetcode】Kth Largest Element in an Array
- Leetcode: Kth Largest Element in an Array
- Kth Largest Element in an Array -- leetcode
- [Leetcode]Kth Largest Element in an Array
- [LeetCode]Kth Largest Element in an Array
- *LeetCode-Kth Largest Element in an Array
- LeetCode----Kth Largest Element in an Array
- LeetCode Kth Largest Element in an Array
- leetcode-Kth Largest Element in an Array
- ecshop二次开发_Logo和版权信息
- 异常:unknow entity
- JDBC中的事务的概念
- Moore's voting algorithm
- Java中对象交换的问题
- [leetcode]Kth Smallest Element in an Array
- 中国牛市
- css常用属性及属性值
- Python之Dijango的“坑” hostname, aliases, ipaddrs = gethostbyaddr(name) UnicodeDecodeError: 'utf-8' cod
- pdo连接数据库及pdo对象的方法介绍
- linux下使用ffmpeg将flv、mp4、rmvb转换为libx264的mp4
- 剑指向offer-树的子结构-php
- MapReduce编程(七) 倒排索引构建
- C++指针