Members
Methods
(static) kthLargestElement(k, nums) → {Object}
Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Implement KthLargest class:
KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums.
int add(int val) Appends the integer val to the stream and returns the element representing the kth largest element in the stream.
For example,
Input: ["KthLargest", "add", "add", "add", "add", "add"]
[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]
Output: [null, 4, 5, 5, 8, 8]
Time Complexity for constructor: O(nlog(k))
Time Complexity for add function: O(nlog(k))
- Source:
- See:
Parameters:
Name | Type | Description |
---|---|---|
k |
number
|
kth position of the element that needs to be returned |
nums |
Array.<number>
|
Stream of numbers |
Returns:
- Type:
-
Object
Object containing add method which will maintain the heap of 'k' size.
(static) lastStoneWeight(stones) → {number}
You are given an array of integers stones where stones[i] is the weight of the ith stone.
Implement KthLargest class:
We are playing a game with the stones. On each turn, we choose the heaviest two stones and smash them together.
Suppose the heaviest two stones have weights x and y with x <= y. The result of this smash is:
If x == y, both stones are destroyed, and
If x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x.
At the end of the game, there is at most one stone left.
Return the weight of the last remaining stone. If there are no stones left, return 0.
For example,
Input: stones = [2,7,4,1,8,1]
Output: 1
Time Complexity: O(n*log(n))
- Source:
- See:
Parameters:
Name | Type | Description |
---|---|---|
stones |
Array.<number>
|
Stones where stones[i] is the weight of the ith stone. |
Returns:
- Type:
-
number
Weight of the last remaining stone.
add(value)
Add the value into the heap.
Time Complexity: O(logN).
- Source:
Parameters:
Name | Type | Description |
---|---|---|
value |
T
|
value that needs to be inserted |
Returns:
void
changeKey() → {value}
Change the value of the key. It will update the value according to the heap type(min/max).
Time Complexity: O(logN).
- Source:
Returns:
- Type:
-
value
The top most item from the heap
extract() → {value}
Remove the top most item from the heap.
Time Complexity: O(logN).
- Source:
Returns:
- Type:
-
value
The top most item from the heap