Design a class to find the **k**th largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.

Your `KthLargest`

class will have a constructor which accepts an integer `k`

and an integer array `nums`

, which contains initial elements from the stream. For each call to the method `KthLargest.add`

, return the element representing the kth largest element in the stream.

**Example:**

int k = 3; int[] arr = [4,5,8,2]; KthLargest kthLargest = new KthLargest(3, arr); kthLargest.add(3); // returns 4 kthLargest.add(5); // returns 5 kthLargest.add(10); // returns 5 kthLargest.add(9); // returns 8 kthLargest.add(4); // returns 8

**Note: **

You may assume that `nums`

‘ length ≥ `k-1`

and `k`

≥ 1.

Try to solve this kind of problem, you can easily think about the heap, but this problem is a little complex. First I build a max-heap, so I can get the initial kth largest element.

Then when we add a number small or equal than the current kth largest element, it will cause nothing, we can just ignore it. When it is larger than the current kth largest element, the original kth largest element need be removed, and the new number should add to the top-k numbers to compare which is the smallest.

So we can use a min-heap save the top-k numbers. If the new number is smaller, don’t touch min-heap, just output the top of the heap.

If the new number is larger, we use it to replace the top of the heap, and minHeapify(1), then we can ensure the top of the heap is the kth largest element, so then we output it.

So the code of the constructor like this:

Method add:

And we add a method replaceTop to min-heap:

Runtime: 61 ms, faster than 66.06% of Java online submissions for Kth Largest Element in a Stream.

Memory Usage: 48.1 MB, less than 42.98% of Java online submissions for Kth Largest Element in a Stream.

After thinking about solution1, we found the max-heap is not necessary. One min-heap can solve this problem too. First, we create an array size is k, make every element in this array is Integer.MIN_VALUE. Then we make it a min-heap, use the add method to add all elements in. We will find out this heap is the top-k elements already. And add more numbers will not change this property. The time complexity is not much different from solution 1. But the code is simpler and easier. We don’t need to change the add and the replaceTop method, we only need a new constructor.

Github: https://github.com/tinyfool/leetcode/tree/master/src/p0703

Want to know more details of heap and heapsort, check my post:Heap and Heap-Sort algorithm.

]]>Given a *n* x *n* matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.

Note that it is the kth smallest element in the sorted order, not the kth distinct element.

**Example:**

matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15] ], k = 8, return 13.

**Note: **

You may assume k is always valid, 1 ≤ k ≤ n^{2}.

I know this problem must have some more elegant solutions, because we have some information of the matrix, but I am processing problems about heap, so I just provide a heap solution. (codes about max-heap see this)

Github: https://github.com/tinyfool/leetcode/tree/master/src/p0378

Want to know more details of heap and heapsort, check my post:Heap and Heap-Sort algorithm.

Find the **k**th largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

**Example 1:**

Input:`[3,2,1,5,6,4]`

and k = 2Output:5

**Example 2:**

Input:`[3,2,3,1,2,4,5,5,6]`

and k = 4Output:4

**Note: **

You may assume k is always valid, 1 ≤ k ≤ array’s length.

I have two solutions.

First one is simple, just two lines, first sort, then output the **k**th element.

Second is not hard too, first I build a max-heap, then output the **k**th element. (codes about max-heap see this)

Github: https://github.com/tinyfool/leetcode/tree/master/src/p0215

Want to know more details of heap and heapsort, check my post:Heap and Heap-Sort algorithm.

Heap is a complete binary tree represented by an array. A binary tree is one kind of tree, every parent node has at most two children, we call them left-subtree and right-subtree.

A perfect binary tree is a binary tree when the layer count is k, it has 2^{k}-1 nodes. Like this:

And we can think a complete binary tree is a perfect binary tree leak or not lack some nodes but must fill the nodes from top to bottom, left to right. It means only can lack some nodes from the right. Like this:

When we use a heap to store this complete binary tree, we can save it as an array like this: [A, B, C, D, E, F, G, H, I, J, K, L]. Use this storage method, we will find out that the index of the root of this tree is 1.

And the index of every parent node is the children node’s index divide to 2. And left sub-node’s index is its parent node’s index multiply 2, right sub-node’s index is its parent node’s index multiply 2 then add 1.

So we get the function to access children and parent nodes.

Then we discuss a data structure, Max-Heap. It is a heap, every parent bigger than its children. So we know in a Max-Heap root is the biggest number. The picture is a Max-Heap and its corresponding array.

You can easy define a Min-Heap, we don’t discuss it now.

If a node of a ** max-heap** smaller than its sub-nodes, it violates the rule of max-heap. If we know its sub-nodes is valid max-heap, we can correct it by a

We make a video demo, 4 is the error node.

This is the code. _A is the array store the heap, and index -1 because in Java array’s index start from 0:

For the Max-Heapify to run, we write a helper function exchange:

Then how can we build a Max-heap from a random complete binary tree? Suppose we have a heap like this:

We can start from the middle of the heap (the 5th node), back to root one by one to perform the max-heapify operation. When it finished, we have a max-heap. This is a demo video for this:

Code like this:

When we look carefully we will find out max-heap is not an ordered data structure. Every parent node is larger than its children, but left sub-node can bigger also can smaller than the right sub-node. We can’t easily get an ordered array just by traverse the binary tree in any way. So how do we use a heap to sort numbers?

We know the root always is the biggest one. So we can swap the root with the last node, then remove the last node from the heap, and max-heapify the root. Then the remaining heap becomes a valid max-heap, we can do this again and again. We always put the largest number at back, so we get an ordered array.

We can start from this max-heap to sort.

And this is our demo video:

Code like this:

And max-heap can support an operation ** ExtractMax**, return the root, remove it, and shrink the heap. We can use it to get the maximum number or the k largest number without sort it first. Code like this:

So we can use max-heap to sort numbers. Or we can use it to get the maximum number or get the k largest number to pay less cost than sort it.

GitHub address：https://github.com/tinyfool/leetcode/blob/master/src/CLRS/HeapSort.java

Write an efficient algorithm that searches for a value in an *m* x *n* matrix. This matrix has the following properties:

- Integers in each row are sorted in ascending from left to right.
- Integers in each column are sorted in ascending from top to bottom.

**Example:**

Consider the following matrix:

[ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ]

Given target = `5`

, return `true`

.

Given target = `20`

, return `false`

.

This problem we tried 4 solutions, ** vertical and “horizontal binary search”** approach,

This is a direct approach, is a divide and conquer way. First, we cut the matrix vertically to the ** top** and

Running time is 52ms, not fast enough. This because we only use one property of the matrix, ** ascending from left to right**, we didn’t use the property of

We need to use binary search in both ways to be faster. When we cut the matrix, we can find out two key points, one is the ** right-bottom** corner

In the code ** p1** is

Running time is 27ms still not fast enough.

I know we can split the matrix into 4 areas to search, but I try to avoid this way. Because code will be really messy. Now we know last way is not fast enough, I have to code in this way. It is not complex to think, cut the matrix into 4 areas, then cut and cut, until there is only one element. We can use the key points (every left-top and right bottom corner of sub-matrixes) to seep up searches.

This thought is not hard, but the code is very complex. You may already find out this is very similar to ** Strassen’s algorithm for matrix multiplication** from Introduction to Algorithms. This is the code:

Running time is 7ms is fast enough.

All these solutions are too complex, can we solve it easily? I tried once expend the matrix to an array, then use a binary search. But I find out the matrix ascending from left to right and ascending from top to bottom, don’t mean it can expend to an ordered array. So directly use a binary search will not get the correct result.

So we only can expend the matrix to an array, and sort it, then use a binary search. The code like this:

Code is very simple but very slow, running time is 610ms, is not very useful. The 4 area solution is best.

Github 地址：https://github.com/tinyfool/leetcode/tree/master/src/p0240

Want to know details of the Divide and conquer, check my post: Leetcode problems of Divide and conquer.

Given an array of size *n*, find the majority element. The majority element is the element that appears **more than** `⌊ n/2 ⌋`

times.

You may assume that the array is non-empty and the majority element always exists in the array.

**Example 1:**

Input:[3,2,3]Output:3

**Example 2:**

Input:[2,2,1,1,1,2,2]Output:2

We provide 3 solutions. ** Hash-map** approach,

This solution is easily understood, we use a hash-map to store counts of elements. The first loop we count every element. The second loop we find the most frequency element, it is our result. Actually, we can use one loop to get the result, a little faster, but it will not change the complexity, so we ignore it.

Because the majority element appears more than half times, so we know if we split the array to ** left** and

First, we sort the array, then one loop to count elements. (And there are a more easy solution, sort and get the middle element, it must be the majority element.)

Github address: https://github.com/tinyfool/leetcode/tree/master/src/p0169

Want to know details of the Divide and conquer, check my post: Leetcode problems of Divide and conquer.

Given an integer array `nums`

, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

**Example:**

Input:[-2,1,-3,4,-1,2,1,-5,4],Output:6Explanation:[4,-1,2,1] has the largest sum = 6.

**Follow up:**

If you have figured out the O(*n*) solution, try coding another solution using the divide and conquer approach, which is more subtle.

Actually, this problem is the same problem as the ** Maximum Subarray problem** from

Github address：https://github.com/tinyfool/leetcode/tree/master/src/p0053

Want to know details of the Divide and conquer, check my post: Leetcode problems of Divide and conquer.

Merge *k* sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

**Example:**

Input:

[

1->4->5,

1->3->4,

2->6

]Output:

1->1->2->3->4->4->5->6

I don’t know how to merge k lists, but we know how to merge two lists from problem 21. So we can merge the first two lists and merge others one by one. This is the brute force solution.

* mergeTwoList* function from problem 21.

How to use ** Divide and conquer** approach to solve this problem? We can naturally think about divide the lists to two half, then divide it again and again, until there are only two linked lists. Then we can use the

In this solution we use a min-heap, it is almost identical to max-heap. We only need to change serval lines to make a max-heap to become min-heap. We use the code described in “Heap and Heap-Sort algorithm“.

Our method is: First, move all data from lists to an array, then use the array to build a min-heap. Finally, we output the current minimum number in a loop, make a LinkedList and return it.

This is the code (Code about min-heap you can find in GitHub files):

Github address: https://github.com/tinyfool/leetcode/tree/master/src/p0023

Want to know detail of heap and heapsort, check my post:Heap and Heap-Sort algorithm.

]]>** Divide and conquer** is a method to solve a complex problem. When we think of a problem too complex or too big, we can try to divide the problem to some easy problems or small problems. Then we try to solve these small/easy problems and combine the results to solve the complex/big problem.

Divide and conquer is easy when you can easily find out how to divide a problem. But a lot of times how to divide a problem is hard. And different problem always needs a different divide approach. So if you want to master all divide and conquer problems you need to do a lot of practices. Only this way you can build a strong understanding of the thought of divide and conquer, and get more feeling of familiarity, and master more method to divide.

Chapter 2.3.1 of * Introduction to Algorithms* introduces

I implement these three algorithms from pseudocode from the book to Java code:

GitHub address：https://github.com/tinyfool/leetcode/blob/master/src/CLRS/DivideAndConquer/MergeSort.java

GitHub address：https://github.com/tinyfool/leetcode/blob/master/src/CLRS/DivideAndConquer/MaximumSubarray.java

GitHub address：https://github.com/tinyfool/leetcode/blob/master/src/CLRS/DivideAndConquer/SquareMatrixMultiply.java

**Helper functions**

**Matrix split and combine functions **

**Matrix add and minus functions**

**Strassen’s algorithm for matrix multiplication**

4 | Median of Two Sorted Arrays | Hard |

23 | Merge k Sorted Lists | Hard |

53 | Maximum Subarray | Easy |

169 | Majority Element | Easy |

215 | Kth Largest Element in an Array | Medium |

218 | The Skyline Problem | Hard |

240 | Search a 2D Matrix II | Medium |

241 | Different Ways to Add Parentheses | Medium |

282 | Expression Add Operators | Hard |

312 | Burst Balloons | Hard |

315 | Count of Smaller Numbers After Self | Hard |

327 | Count of Range Sum | Hard |

493 | Reverse Pairs | Hard |

514 | Freedom Trail | Hard |

426 | Convert Binary Search Tree to Sorted Doubly Linked List | Medium |

903 | Valid Permutations for DI Sequence | Hard |

932 | Beautiful Array | Medium |

973 | K Closest Points to Origin |

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

**Example:**

Input:1->2->4, 1->3->4Output:1->1->2->3->4->4

This problem has a straightforward approach. We can traverse both linked lists at the same time. Every turn we choose the smaller one and move the corresponding linked list to the next node. In the process, if one of linked list is empty, then put another linked list to the tail of the result linked list.

This is the code:

And we can use recursion to make the code easier and clearer. First, if one of linked list is empty, then return another linked list. Then if the current first node of l1 is smaller than or equal with l2, we change the second node of l1 to the result of the origin second node of l1 merge with l2, vice-versa.

code download url：https://github.com/tinyfool/leetcode/tree/master/src/p0021