Kth Smallest Element in Unsorted Array
(referrence: GeeksforGeeks, Kth Largest Element in Array)
This is a common algorithm problem appearing in interviews.
There are four basic solutions.
Solution 1 -- Sort First
A Simple Solution is to sort the given array using a O(n log n) sorting algorithm like Merge Sort,Heap Sort, etc and return the element at index k-1 in the sorted array. Time Complexity of this solution is O(n log n).
public class Solution{
public int findKthSmallest(int[] nums, int k) {
Arrays.sort(nums);
return nums[k];
}
}
Solution 2 -- Construct Min Heap
A simple optomization is to create a Min Heap of the given n elements and call extractMin() k times.
To build a heap, time complexity is O(n). So total time complexity is O(n + k log n).
Using PriorityQueue(Collection<? extends E> c), we can construct a heap from array or other object in linear time.
By defaule, it will create a min-heap.
Example
public int generateHeap(int[] nums) {
int length = nums.length;
Integer[] newArray = new Integer[length];
for (int i = 0; i < length; i++)
newArray[i] = (Integer)nums[i];
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(Arrays.asList(newArray));
}
Comparator cmp = Colletions.reverseOrder();
Solution 3 -- Use Max Heap
1. Build a max-heap of size k. Put nums[0] to nums[k - 1] to heap.
2. For each element after nums[k - 1], compare it with root of heap.
a. If current >= root, move on.
b. If current < root, remove root, put current into heap.
3. Return root.
Time complexity is O((n - k) log k).
(Java: PriorityQueue)

(codes)
public class Solution {
public int findKthSmallest(int[] nums, int k) {
// Construct a max heap of size k
int length = nums.length;
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(k, Collections.reverseOrder());
for (int i = 0; i < k; i++)
pq.add(nums[i]);
for (int i = k; i < length; i++) {
int current = nums[i];
int root = pq.peek();
if (current < root) {
// Remove head
pq.poll();
// Add new node
pq.add(current);
}
}
return pq.peek();
}
}
Solution 4 -- Quick Select
public class Solution {
private void swap(int[] nums, int index1, int index2) {
int tmp = nums[index1];
nums[index1] = nums[index2];
nums[index2] = tmp;
}
// Pick last element as pivot
// Place all smaller elements before pivot
// Place all bigger elements after pivot
private int partition(int[] nums, int start, int end) {
int pivot = nums[end];
int currentSmaller = start - 1;
for (int i = start; i < end; i++) {
// If current element <= pivot, put it to right position
if (nums[i] <= pivot) {
currentSmaller++;
swap(nums, i, currentSmaller);
}
}
// Put pivot to right position
currentSmaller++;
swap(nums, end, currentSmaller);
return currentSmaller;
}
public int quickSelect(int[] nums, int start, int end, int k) {
int pos = partition(nums, start, end)
if (pos == k - 1)
return nums[pos];
if (pos < k - 1)
return quickSelect(nums, pos + 1, end, k - (pos - start + 1));
else
return quickSelect(nums, start, pos - 1, k);
}
}
The worst case time complexity of this method is O(n2), but it works in O(n) on average.
Kth Smallest Element in Unsorted Array的更多相关文章
- [LeetCode] Kth Smallest Element in a BST 二叉搜索树中的第K小的元素
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Not ...
- algorithm@ find kth smallest element in two sorted arrays (O(log n time)
The trivial way, O(m + n): Merge both arrays and the k-th smallest element could be accessed directl ...
- leetcode面试准备:Kth Largest Element in an Array
leetcode面试准备:Kth Largest Element in an Array 1 题目 Find the kth largest element in an unsorted array. ...
- [Swift]LeetCode230. 二叉搜索树中第K小的元素 | Kth Smallest Element in a BST
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Not ...
- 【LeetCode】215. Kth Largest Element in an Array (2 solutions)
Kth Largest Element in an Array Find the kth largest element in an unsorted array. Note that it is t ...
- Leetcode 之 Kth Largest Element in an Array
636.Kth Largest Element in an Array 1.Problem Find the kth largest element in an unsorted array. Not ...
- [Leetcode Week11]Kth Largest Element in an Array
Kth Largest Element in an Array 题解 题目来源:https://leetcode.com/problems/kth-largest-element-in-an-arra ...
- 网易2016 实习研发工程师 [编程题]寻找第K大 and leetcode 215. Kth Largest Element in an Array
传送门 有一个整数数组,请你根据快速排序的思路,找出数组中第K大的数. 给定一个整数数组a,同时给定它的大小n和要找的K(K在1到n之间),请返回第K大的数,保证答案存在. 测试样例: [1,3,5, ...
- LN : leetcode 215 Kth Largest Element in an Array
lc 215 Kth Largest Element in an Array 215 Kth Largest Element in an Array Find the kth largest elem ...
随机推荐
- Android Studio代码着色插件
文章将给大家分享Studio中代码高亮插件,个人觉得换个代码着色方式还是挺有必要的,起码让视觉上有个变换,感官上爽一些.就像吃惯了大鱼大肉,偶尔也来点青菜萝卜吧.以下是个人喜欢的几款,给个效果图大家看 ...
- Game of Life 解答
Question According to the Wikipedia's article: "The Game of Life, also known simply as Life, is ...
- Populating Next Right Pointers in Each Node II 解答
Question Follow up for problem "Populating Next Right Pointers in Each Node". What if the ...
- [置顶] vi、akw和sed总结
- LinQ 语法基础
LINQ (Language-Integrated Query,语言集成查询). LINQ to Objects.LINQ to SQL.LINQ to DataSet和LINQ to XML,它们分 ...
- BZOJ 4541 【HNOI2016】 矿区
题目链接:矿区 这道题去年暑假就想写了,但是一直拖拉,以至于现在才来写这道题.以前一直在刻意回避几何类的题目,但到了现在这个时候,已经没有什么好害怕的了. 正巧今天神犇\(xzy\)讲了这道题,那我就 ...
- 一个简单的面试题 很多人也会懵 i++ 和++i的区别
以下分别输出i的值分别为多少 NSInteger i = 0 ; NSLog(@"%ld",i++); NSLog(@"%ld",i++); NSLog(@&q ...
- python学习之路-5 基础进阶篇
本篇涉及内容 双层装饰器字符串格式化 双层装饰器 装饰器基础请点我 有时候一个功能需要有2次认证的时候就需要用到双层装饰器了,下面我们来通过一个案例详细介绍一下双层装饰器: 执行顺序:自上而下 解释顺 ...
- 再一次强调,ORACLE外键必须加索引
外键加索引是常识,必须牢记.本来不想写这样的简单案例.可是连续遇到好几起外键不加索引导致性能问题,所以还是写一下. 一个兄弟问我 delete from Sa_Sales_Comm_Detail s ...
- boost库asio详解1——strand与io_service区别
namespace { // strand提供串行执行, 能够保证线程安全, 同时被post或dispatch的方法, 不会被并发的执行. // io_service不能保证线程安全 boost::a ...