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 ...
随机推荐
- 快速批量导入庞大数据到SQL SERVER数据库(ADO.NET)
原文地址:http://www.cnblogs.com/chenxizhang/archive/2008/11/11/1331060.html 如果你需要在程序中批量插入成千上万行的数据,你会怎么编写 ...
- HDU1394 Minimum Inversion Number(线段树OR归并排序)
Minimum Inversion Number Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java ...
- safari浏览器cookie问题
这个题目可能有点大了,这里主要讨论一种解决safari浏览器阻止第三方cookie问题. 场景 公司存在多个域名(a.com,b.com,co.com)这些域名应该统一 ...
- c、c++知识点
一. (1)在linux下类似uint8_t这样的文件定义在头文件<stdint.h>里面 (2)截取了stdint.h头文件里的一些常用部分 二.c++中c_str()用法 函数返回 ...
- Runtime运行时机制
Runtime 又叫运行时,是一套底层的 C 语言 API,其为 iOS 内部的核心之一,我们平时编写的 OC 代码,底层都是基于它来实现的 我们需要了解的是 Objective-C 是一门动态语言, ...
- Hacker(七)----黑客常用术语和DOS命令
掌握基本的黑客术语和DOS命令是一名黑客最基本的技能,黑客术语能够实现自己和其他人之间的正常交流.DOS命令就是DOS操作系统的命令,它是一种面向磁盘的操作命令.黑客在入侵目标主机的过程中经常会使用这 ...
- [HeadFirst-JSPServlet学习笔记][第一章:前言与概述]
第一章 前言与概述 web服务器做什么? 答:接收客户请求,然后向客户返回结果 web客户做什么? 答:此处客户指浏览器,web客户允许用户请求服务器上的某个资源,并向用户展现请求的结果. html ...
- EffectiveC#03--用委托表示回调,用事件定义对外接口
1.回调的场景:我给了儿子一个任务且他可以报告状态来(重复的)打断我.而我在等待他完成任务的每一个部份时不用阻塞我自己的进程.他可以在有重要(或者事件)状态报告时,可以定时的打断我,或者向我询求帮助 ...
- ArcEngine颜色可视化
AE中利用.NET中的ColorDialog对话框,将color对象转化为ArcEngine中的IRgbColor (1)在实现颜色选择之前,需定义这两种颜色之间的转换函数 //Color转换为Rgb ...
- Android-----输入法的显示和隐藏
/** * 控制手机虚拟键盘的显示和隐藏 */public class InputMethodUtil { /** * 隐藏虚拟键盘 * @param v 参数v为获取焦点对象view */ pub ...