(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. CF 584B Kolya and Tanya

    题目大意:3n个人围着一张桌子,给每个人发钱,可以使1块.2块.3块,第i个人的金额为Ai.若存在第个人使得Ai + Ai+n + Ai+2n != 6,则该分配方案满足条件,求所有的满足条件的方案数 ...

  2. javascript运算符整理

    说起运算符,基本上各类编程语言中都会涉及,使用方法大同小异.今天在这里以javascript做简单的整理. 总得来说运算符还是比较的多,大致可以分为以下几种类型: 一元运算符 位运算符 布尔运算符 乘 ...

  3. poj 2229 Sumsets(dp 或 数学)

    Description Farmer John commanded his cows to search . Here are the possible sets of numbers that su ...

  4. Nexus 刷机

    @echo offfastboot flash bootloader bootloader-hammerhead-hhz12k.imgfastboot flash radio radio-hammer ...

  5. Oracle sga、pga介绍改动

    oracle推荐OLTP(on-line TransactionProcessing)系统oracle占系统总内存的80%,然后再分配80%给SGA,20%给PGA.也就是 SGA=system_to ...

  6. (3)选择元素——(6)属性选择器(Attribute selectors)

    Attribute selectors are a particularly helpful subset of CSS selectors. They allow us to specify an ...

  7. Android——编译odex保护

    编译过android源代码的可能试验过改动编译类型.android的初始化编译配置可參考Android--编译系统初始化设置 一.TARGET_BUILD_VARIANT=user 当选择的编译类型为 ...

  8. Android 打造自己的个性化应用(二):应用程序内置资源实现换肤功能

    通过应用程序内置资源实现换肤,典型的应用为QQ空间中换肤的实现. 应用场景为: 应用一般不大,且页面较少,风格相对简单,一般只用实现部分资源或者只用实现背景的更换. 此种换肤方式实现的思路: 1. 把 ...

  9. cocoapods在OS X Yosemite系统中报错

    之前使用cocoapods一直是正常使用的,刚换了电脑,使用pod install的时候报错: /System/Library/Frameworks/Ruby.framework/Versions/2 ...

  10. .Net平台下ActiveMQ入门实例(转)

    1.ActiveMQ简介 先分析这么一个场景:当我们在网站上购物时,必须经过,下订单.发票创建.付款处理.订单履行.航运等.但是,当用户下单后,立即跳转到"感谢那您的订单" 页面. ...