“This is the fourth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
Brothers! I’m a big bear…
Today I’m going to show you the problem of rotating linked lists. Let’s see
So let’s first look at this problem what is the KTH largest element in the data stream
The literal meaning is actually quite vague let’s see if we pass in K=3 nums=[4,5,8,2]
The add method passes in 3 so nums=[4,5,8,2,3] and the third element is 4
The add method passes 5 so that nums=[4,5,8,2,3,5] the third element is 5
The add method passes in 10 so that nums=[4,5,8,2,3,5,10] the third element is 5
The add method passes in 9 so that nums=[4,5,8,2,3,5,10,9] and the third element is 8
The add method passes in 4 so nums=[4,5,8,2,3,5,10,9,4] the third element is 8
As in the example, the problem is simple: the elements after the array push –> in reverse order [k-1] are what we want
var KthLargest = function (k, nums) {
this.nums = nums.sort((a, b) = > b - a)
this.k = k
};
/ * * *@param {number} val
* @return {number}* /
KthLargest.prototype.add = function (val) {
this.nums.push(val)
return this.nums.sort((a, b) = > b - a)[this.k - 1]};Copy the code
Brothers is not very simple!!