LeetCode: Find Median from Data Stream Solution
Insert and keep the array sortedApproach
Approach 1 (sorting): sort the array on every insertion
Approach 2 (heap): insert but still keep the array sorted (efficient)
1var MedianFinder = function () {2 this.arr = []3}45/**6 * @param {number} num7 * @return {void}8 */9MedianFinder.prototype.addNum = function (num) {10 this.arr.push(num)11 this.arr.sort((a, b) => a - b)12}1314/**15 * @return {number}16 */17MedianFinder.prototype.findMedian = function () {18 const arrLength = this.arr.length19 const midIndex = Math.floor(arrLength / 2)2021 if (arrLength % 2 === 0) {22 return (this.arr[midIndex] + this.arr[midIndex - 1]) / 223 } else {24 return this.arr[midIndex]25 }26}
Implementation (Heap)
1var MedianFinder = function () {2 this.arr = []3}45/**6 * @param {number} num7 * @return {void}8 */9MedianFinder.prototype.addNum = function (num) {10 let [left, right] = [0, this.arr.length - 1]11 while (left <= right) {12 let mid = Math.floor((left + right) / 2)13 if (num >= this.arr[mid]) {14 right = mid - 115 } else {16 left = mid + 117 }18 }19 this.arr.splice(left, 0, num)20}2122/**23 * @return {number}24 */25MedianFinder.prototype.findMedian = function () {26 const mid = Math.floor(this.arr.length / 2)27 return this.arr.length % 2 === 028 ? (this.arr[mid - 1] + this.arr[mid]) / 229 : this.arr[mid]30}
Comments
Loading comments...
Tags
leetcode
sorting
heap
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.