Vous êtes sur la page 1sur 5

2/3/2019 Leetcode: Find kth number in m sorted arrays

Code Fun

Leetcode: Find kth number in m sorted arrays


Date Sun 09 November 2014 By Xiaoxiang Wu Category Leetcode. Tags 

1. Median of Two Sorted Arrays


There are two sorted arrays A and B of size m and n respectively. Find the median of the two
sorted arrays. The overall run time complexity should be O(log (m+n)).

Problem
1. How is the elements sorted? large to small? small to large?
2. What to return if both arrays are empty

Analysis
Method 1: Merge two lists
Since the two lists are sorted, we can compare the first element of two arrays, and the smaller one must be the
smallest number in the two arrays. Then we contine to compare the second element of the array that contains the
smallest element with the first element of the other array.

We keep doing this until we find the median of the two lists.

Although this is not the optimal solution for this problem, it can be easily extended to the second question that we
will discuss later.

complexity
Time: O(N)

Space: O(1)

Method 2
Supposed we have two arrays A and B (A is shorter than B) and we want to find the kth number in the two sorted
arrays.

We can pick the first k/2 numbers from the first array and (k - k/2) numbers from the other array. In this way, we
have totally picked k number from the two arrays. Then we compare the last element of this two lists of numbers.
If the last element in the first list is greater than the last element in the second list, then we can delete the first (k -
k/2) numbers from the second array.

Why can we do this? Since we have picked the first k elements from these two arrays. All the elements in the
second subarray is smaller than the last element in the first subarray, they must be smaller than the kth number in
the two arrays.

After this, we recursively find the answer in the remaining arrays. Now, instead of finding the kth number, we want
to find the (k-x)th number, where x is the number of elements deleted in the array.

Example:
1, 3, 5, 6, 8, 9
0, 2, 4, 10, 12
We want to find the 5th smallest number.
https://wxx5433.github.io/leetcode-find-kth-number-in-m-sorted-arrays.html 1/5
2/3/2019 Leetcode: Find kth number in m sorted arrays

k = 5, and k/2 = 2. So we select {1, 3} from the first array and select {0, 2, 4} from the second array. (Actually, we
only need to pick 3 and 4)

Then we compare 3 and 4 . Since 3 is smaller than 4, it is impossible that {1, 3} contains element that is the 5th
number. We can safely delete {1, 3} from the first array.

Since we have remove two elements smaller than the 5th number, we want to find the (5-2) = 3th number from the
remaining arrays, which is {5, 6, 8, 9}, {0, 2, 4, 10, 12}.

Then we continue to compare 5 and 2, and safely remove {0, 2}.

Now we want to find the 1st smallest number from {5, 6, 8, 9}, {4, 10, 12}. We only need to pick the smaller
number from the head of the two subarrays, which is 4.

We can check that 4 is the 5th smallest number in the two arrays.

To find the median of two sorted arrays. We can apply the method stated above.

Corner cases
1. one array is empty, return the kth number of the nonempty array.
2. even number of total elements, we need to find two middle numbers and calculate the median.
3. k may be larger than the length of the smaller array.

Complexity
Time: O(logk). In the worst case, we want to find the (m + n)th number from the two lists. That is O(log(m+n)).

Space: O(1)

Code
public class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int totalLen = nums1.length + nums2.length;
int mid = (totalLen + 1) / 2;
if (totalLen % 2 != 0) {
return getKthNumber(nums1, 0, nums2, 0, mid);
} else {
return (getKthNumber(nums1, 0, nums2, 0, mid)
+ getKthNumber(nums1, 0, nums2, 0, mid + 1)) / 2;
}
}

private double getKthNumber(int[] nums1, int start1,


int[] nums2, int start2, int k) {
int remainingSize1 = nums1.length - start1;
int remainingSize2 = nums2.length - start2;

// make sure the first array is shorter


if (remainingSize1 > remainingSize2) {
return getKthNumber(nums2, start2, nums1, start1, k);
} else if (remainingSize1 == 0) { // the shorter array is empty
return nums2[start2 + k - 1];
}

if (k == 1) {
return Math.min(nums1[start1], nums2[start2]);
}

int offset = Math.min(k / 2, remainingSize1); // offset of array 1


https://wxx5433.github.io/leetcode-find-kth-number-in-m-sorted-arrays.html 2/5
2/3/2019 Leetcode: Find kth number in m sorted arrays
int i = start1 + offset;
int j = start2 + k - offset;

if (nums1[i - 1] < nums2[j - 1]) {


return getKthNumber(nums1, i, nums2, start2, k - offset);
} else {
return getKthNumber(nums1, start1, nums2, j, offset);
}
}
}

2. Find the kth numer in m sorted arrays


Analysis
We can apply the first method described above. First we push all the first elements in all arrays into a heap.

Then every time we pop out the top of the heap and then push the next element from the array where the pop-out
element comes from.

We keep doing this until find the kth number.

To implement this, we need to define a data structure to record which list the node in the heap comes from. We
can very easily define it like this.

class Node implements Comparable<Node>{


int value;
int listNum;

public Node(int val) {


value = val;
}

@Override
public int compareTo(Node n) {
return value - n.value;
}
}

Then we can push the node into the heap.

Complexiy
Time: O(klogm), every time we operate the heap, we need log(m) time since we have m elements in the heap.

Space: O(k). We only maintain k nodes in the heap all the time.

 BLOGROLL
 Pelican
 Python.org
 Jinja2
 You can modify those links in your config file

 SOCIAL
 atom feed

https://wxx5433.github.io/leetcode-find-kth-number-in-m-sorted-arrays.html 3/5
2/3/2019 Leetcode: Find kth number in m sorted arrays

You can add links in your config file


Another social link

 CATEGORIES
 Algorithm
 Google
 Interview

 Leetcode
 LinkedIn

 TAGS
 Traversal
 Two Pointer

 BFS

 Bucket Sort

 Math
 HashSet

 Binary Search Tree

 Memo
 Bucket

 Subarray
 File

 Two Pointers
 Reconstruct Tree

 LinkedList
 Array
 Union Find
 Parallel

 Binary Search

 Radix Sort

 DP
 Trie

 Data Structure

 Sliding Window
 Path Sum

 Greedy

 Recursion
 Sort

 Topological Sort

 Divide and Conquer

 Set

 Bottom Up

https://wxx5433.github.io/leetcode-find-kth-number-in-m-sorted-arrays.html 4/5
2/3/2019 Leetcode: Find kth number in m sorted arrays

 Level-Order Traversal
 Shortest Path

 BST
 Interview
 Iterator
 Heap

 Data Strucutre

 Graph
 Design

 Circular

 Tree
 Binary Tree

 Bit Manipulation
 DFA

 Stack
 BackTrace

 String
 Rotate

 Map
 DFS

Proudly powered by Pelican , which takes great advantage of Python .

The theme is from Bootstrap from Twitter , and Font-Awesome , thanks!

https://wxx5433.github.io/leetcode-find-kth-number-in-m-sorted-arrays.html 5/5

Vous aimerez peut-être aussi