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

Java Arrays.sort()

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

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

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<Integer> pq = new PriorityQueue<Integer>(Arrays.asList(newArray));
7     }

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)

 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<Integer> pq = new PriorityQueue<Integer>(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 head
13                 pq.poll();
14                 // Add new node
15                 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.

时间: 2024-11-10 22:45:35

Kth Smallest Element in Unsorted Array的相关文章

good article————K’th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)

这是本人在研究leetcode中Median of Two Sorted Arrays一题目的时候看到一篇文章,觉得非常好,其中对快速排序重新实现. 文章来源于http://www.geeksforgeeks.org/这个网站. We recommend to read following post as a prerequisite of this post. K'th Smallest/Largest Element in Unsorted Array | Set 1 Given an ar

leetcode Kth Largest Element in an Array

题目连接 https://leetcode.com/problems/kth-largest-element-in-an-array/ Kth Largest Element in an Array Description Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct eleme

[email&#160;protected] 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 directly. Merging would require extra space of O(m+n). The linear run time is pretty good, but could we improve it even further? A better way, O(k): There is

LeetCode OJ 215. Kth Largest Element in an Array 堆排序求解

题目链接:https://leetcode.com/problems/kth-largest-element-in-an-array/ 215. Kth Largest Element in an Array My Submissions Question Total Accepted: 43442 Total Submissions: 136063 Difficulty: Medium Find the kth largest element in an unsorted array. Not

Leetcode题解(3):L215/Kth Largest Element in an Array

L215: Kth Largest Element in an Array Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. For example, Given [3,2,1,5,6,4] and k = 2, return 5. Note: You may as

堆排序 &amp;&amp; Kth Largest Element in an Array

堆排序 堆节点的访问 通常堆是通过一维数组来实现的.在数组起始位置为0的情形中: 父节点i的左子节点在位置(2*i+1); 父节点i的右子节点在位置(2*i+2); 子节点i的父节点在位置floor((i-1)/2); 堆的操作 在堆的数据结构中,堆中的最大值总是位于根节点(在优先队列中使用堆的话堆中的最小值位于根节点).堆中定义以下几种操作: 最大堆调整(Max_Heapify):将堆的末端子节点作调整,使得子节点永远小于父节点 创建最大堆(Build_Max_Heap):将堆所有数据重新排序

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

传送门 有一个整数数组,请你根据快速排序的思路,找出数组中第K大的数. 给定一个整数数组a,同时给定它的大小n和要找的K(K在1到n之间),请返回第K大的数,保证答案存在. 测试样例: [1,3,5,2,2],5,3 返回:2 note: 注意手写快排的时候: while(i < j) { while(j > i && a[j] > a[left]) j--; while(i < j && a[i] <= a[left]) i++; if(i

【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 the kth largest element in the sorted order, not the kth distinct element. For example,Given [3,2,1,5,6,4] and k = 2, return 5. Note: You may assume k

leetcode_215题——Kth Largest Element in an Array(堆排序)

Kth Largest Element in an Array Total Accepted: 13165 Total Submissions: 48240My Submissions Question Solution Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct elemen