We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
functionrunningMedian(a){// Write your code hereconstcurrentArr=[];constresults=[];for(leti=0;i<a.length;i++){if(!currentArr.length){currentArr.push(a[i]);}elseif(a[i]<currentArr[0]){currentArr.unshift(a[i]);}elseif(a[i]>currentArr[currentArr.length-1]){currentArr.push(a[i])}else{// seems like we need to insert somewhere in the middleletindex=0;// Find the correct index to insert the new numberwhile(index<a.length&¤tArr[index]<a[i]){index++;}// Insert the new number at the found indexcurrentArr.splice(index,0,a[i]);}// calculate the median for current listif(currentArr.length%2===0){results.push(((currentArr[(currentArr.length/2)-1]+currentArr[currentArr.length/2])/2).toFixed(1));}else{results.push(currentArr[Math.floor(currentArr.length/2)].toFixed(1));}}returnresults;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Find the Running Median
You are viewing a single comment's thread. Return to all comments →
JS