# 2019 算法面试相关(leetcode)--优先队列

0.453字数 1433阅读 814

2019 iOS面试题大全---全方面剖析面试
2018 iOS面试题---算法相关
1、七种常见的数组排序算法整理(C语言版本)
2、2019 算法面试相关(leetcode)--数组和链表
3、2019 算法面试相关(leetcode)--字符串
4、2019 算法面试相关(leetcode)--栈和队列
5、2019 算法面试相关(leetcode)--优先队列
6、2019 算法面试相关(leetcode)--哈希表
7、2019 算法面试相关(leetcode)--树、二叉树、二叉搜索树
8、2019 算法面试相关(leetcode)--递归与分治
9、2019 算法面试相关(leetcode)--贪心算法
10、2019 算法面试相关(leetcode)--动态规划(Dynamic Programming)
11、2019 算法面试相关(leetcode)--动态规划之背包问题

int k = 3;
int[] arr = [4,5,8,2];
KthLargest kthLargest = new KthLargest(3, arr);

``````/**
* @param {number} k
* @param {number[]} nums
*/
var KthLargest = function(k, nums) {

this.nums = nums.sort((a, b) => a - b)

if(nums.length >= k) this.nums = this.nums.slice(nums.length - k,nums.length)

this.k = k
};

/**
* @param {number} val
* @return {number}
*/

if(!this.nums.length || (this.nums.length < this.k && val <= this.nums[0])) this.nums.unshift(val)

else if(val > this.nums[0]){

if(this.nums.length >= this.k) this.nums.shift()

let l = 0,r = this.nums.length - 1

while(l <= r){

let m = Math.floor((l + r)/2)

if(this.nums[m] < val) l = m + 1

else r = m - 1
}

this.nums.splice(l,0,val)
}

return this.nums[0]
};
``````

[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7

``````var maxSlidingWindow = function(nums, k) {

if(!nums || !nums.length) return []

let win = []

let result = []

for(let i = 0; i < nums.length; i++){

if(i >= k && win[0] <= i - k) win.splice(0,1)

while(win.length && nums[i] >= nums[win[win.length - 1]]){

win.pop()
}

win.push(i)

if(i >= k - 1) result.push(nums[win[0]])
}

return result
};
``````

``````/**
* @param {string[]} words
* @param {number} k
* @return {string[]}
*/
var topKFrequent = function(words, k) {

let q = []

let dic = {}

for (const ch of words.sort()) {

dic[ch] = 1 + (dic[ch] || 0)
}

for (const key in dic) {

if(!q.length || (q.length < k && dic[key] <= dic[q[q.length - 1]])) q.push(key)

else if(dic[key] > dic[q[q.length - 1]]){

if(q.length >= k) q.pop()

let l = 0,r = q.length - 1

while(l <= r){

let m = Math.floor((l + r)/2)

if(dic[q[m]] >= dic[key]) l = m + 1

else r = m - 1
}

q.splice(l,0,key)
}
}

return q
};
``````