在2022年二月份有很多前端的朋友面試大廠會問到了js 判斷數(shù)組第二大的數(shù)的題(其實就是一道算法題抚岗,在力扣題號為:215闺兢,題目為:數(shù)組中的第K個最大元素卤妒。
<script type="text/javascript">
//訪問網(wǎng)址:https://xuexiluxian.cn/
var findKthLargest = function(nums, k) {
let arr = new MinHeap();
nums.forEach(item=>{
arr.insert( item );
if( arr.size() > k ){
arr.pop();
}
})
return arr.peek();
};
findKthLargest([3,2,1,5,6,4],2);
class MinHeap{
constructor(){
this.heap = [];
}
//換位置
swap(i1,i2){
const temp = this.heap[i1];
this.heap[i1] = this.heap[i2];
this.heap[i2] = temp;
}
//找到父節(jié)點
getParentIndex( index ){
return Math.floor( (index-1)/2 );
}
//上(前)移操作
up( index ){
//如果是0就不移動了
if( index ==0 )return;
const parentIndex = this.getParentIndex( index );
//如果父元素大于當(dāng)前元素,就開始移動
if( this.heap[parentIndex] > this.heap[index] ){
this.swap( parentIndex , index );
this.up( parentIndex );
}
}
//獲取左側(cè)子節(jié)點
getLeftIndex( index ){
return index * 2 + 1;
}
//獲取右側(cè)子節(jié)點
getRightIndex( index ){
return index * 2 + 2;
}
//下(后)移操作
down( index ){
const leftIndex = this.getLeftIndex( index );
const rightIndex = this.getRightIndex( index );
if( this.heap[leftIndex] < this.heap[index] ){
this.swap(leftIndex,index);
this.down( leftIndex );
}
if( this.heap[rightIndex] < this.heap[index] ){
this.swap(rightIndex,index);
this.down( rightIndex );
}
}
//添加元素
insert( value ){
this.heap.push( value );
this.up( this.heap.length-1 );
}
//刪除堆頂
pop(){
this.heap[0] = this.heap.pop();
this.down( 0 );
}
//獲取堆頂
peek(){
return this.heap[0]
}
size(){
return this.heap.length;
}
}
</script>