博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Kth Smallest Element in Unsorted Array
阅读量:5241 次
发布时间:2019-06-14

本文共 3613 字,大约阅读时间需要 12 分钟。

(referrence: , )

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

1 public class Solution{2     public int findKthSmallest(int[] nums, int k) {3         Arrays.sort(nums);4         return nums[k];5     }6 }

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

1 public int generateHeap(int[] nums) {2         int length = nums.length;3         Integer[] newArray = new Integer[length];4         for (int i = 0; i < length; i++)5             newArray[i] = (Integer)nums[i];6         PriorityQueue
pq = new PriorityQueue
(Arrays.asList(newArray));7 }

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)

1 public class Solution { 2     public int findKthSmallest(int[] nums, int k) { 3         // Construct a max heap of size k 4         int length = nums.length; 5         PriorityQueue
pq = new PriorityQueue
(k, Collections.reverseOrder()); 6 for (int i = 0; i < k; i++) 7 pq.add(nums[i]); 8 for (int i = k; i < length; i++) { 9 int current = nums[i];10 int root = pq.peek();11 if (current < root) {12 // Remove head13 pq.poll();14 // Add new node15 pq.add(current);16 }17 }18 return pq.peek();19 }20 }

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.

 

转载于:https://www.cnblogs.com/ireneyanglan/p/4865541.html

你可能感兴趣的文章
如何解决click事件的重复触发问题
查看>>
2016寒假自学笔记
查看>>
VC++2012编程演练数据结构《21》二叉排序树
查看>>
Easyui NumberBox格式化展示
查看>>
转载:ASP.NET Core 在 JSON 文件中配置依赖注入
查看>>
socket初识
查看>>
磁盘测试工具
查看>>
代码变量、函数命名神奇网站
查看>>
redis cli命令
查看>>
Problem B: 占点游戏
查看>>
python常用模块之sys, os, random
查看>>
HDU 2548 A strange lift
查看>>
Linux服务器在外地,如何用eclipse连接hdfs
查看>>
react双组件传值和传参
查看>>
BNU29140——Taiko taiko——————【概率题、规律题】
查看>>
POJ 2289——Jamie's Contact Groups——————【多重匹配、二分枚举匹配次数】
查看>>
java 得到以后的日期
查看>>
[Kaggle] Sentiment Analysis on Movie Reviews
查看>>
python安装easy_intall和pip
查看>>
HDU1004
查看>>