(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).

Java Arrays.sort()

 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).

Java Priority Queue

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 example

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的更多相关文章

  1. [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 ...

  2. 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 ...

  3. leetcode面试准备:Kth Largest Element in an Array

    leetcode面试准备:Kth Largest Element in an Array 1 题目 Find the kth largest element in an unsorted array. ...

  4. [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 ...

  5. 【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 ...

  6. 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 ...

  7. [Leetcode Week11]Kth Largest Element in an Array

    Kth Largest Element in an Array 题解 题目来源:https://leetcode.com/problems/kth-largest-element-in-an-arra ...

  8. 网易2016 实习研发工程师 [编程题]寻找第K大 and leetcode 215. Kth Largest Element in an Array

    传送门 有一个整数数组,请你根据快速排序的思路,找出数组中第K大的数. 给定一个整数数组a,同时给定它的大小n和要找的K(K在1到n之间),请返回第K大的数,保证答案存在. 测试样例: [1,3,5, ...

  9. 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 ...

随机推荐

  1. dig命令(转载)

    dig命令使用大全(linux上域名查询) 可以这样说,翻译本篇文档的过程就是我重新学习DNS的过程,dig命令可以帮助我们学习DNS的原理,配置,以及其查询过程.以前使用dig仅仅是查询一下A记录或 ...

  2. Unity 代码检测单击,双击,拖放

    今天小伙伴问我如何自己写一段代码检测 单击 双击 和 拖放.于是就写了这段代码O(∩_∩)O~ 代码如下: using UnityEngine; using System.Collections; p ...

  3. 多线程程序 怎样查看每个线程的cpu占用

    可以用下面的命令将 cpu 占用率高的线程找出来: ps H -eo user,pid,ppid,tid,time,%cpu,cmd --sort=%cpu 这个命令首先指定参数'H',显示线程相关的 ...

  4. MFC读写配置文件

    void CFileTextDoc::OnIniread() { // TODO: Add your command handler code here CString strStudName;   ...

  5. linux修改系统时间

    当你把linux还原到某个点的时候,vmware帮不了你把系统时间也给重设了.所以这时候就要手工来搞.关于咋设linux时间.网上介绍也很多,但是都是抄来抄去的东西.那怎么才能高效快捷的设置系统时间呢 ...

  6. Zabbix使用外部邮箱服务器发送邮件报警

    本来是想自己写一篇文章的,但是看到发现网上有写的不错的,于是乎又抄别人的文章,作为记录. 使用外部邮箱来发生邮件明显好处就是防止其他邮箱服务器当垃圾邮件处理,另一方面能降低收邮件延迟. 下面开始进行使 ...

  7. fastclick.js介绍

    原文地址:http://www.uedsc.com/fastclick.html 用途:去掉移动端click事件的300ms的延迟. 延迟为什么存在   …在移动浏览器中,当你点击按钮的单击事件时,将 ...

  8. SQL Server 2008 geometry 数据类型

    摘自SQL Server 2008帮助 平面空间数据类型 geometry 是作为 SQL Server 中的公共语言进行时 (CLR) 数据类型实现的.此类型表示欧几里得(平面)坐标系中的数据. 注 ...

  9. hadoop下载

    1.输入网址: http://mirrors.cnnic.cn/apache/hadoop/common/ 2.选择需要的版本进行点击下载

  10. 关于降低android手机摄像头预览分辨率

    假设现在有这样一个需求需要一直开着手机摄像头 但是不做任何拍照动作 但是每个手机的相机分辨率都不同 而默认预览的时候参数是最大分辨率 这样有时候就回导致电量损耗的加快 所以我们可以采取降低相机分辨率的 ...