zoukankan      html  css  js  c++  java
  • [Algorithm] Median Maintenance algorithm implementation using TypeScript / JavaScript

    The median maintenance problem is a common programming challenge presented in software engineering job interviews.

    In this lesson we cover an example of how this problem might be presented and what your chain of thought should be to tackle this problem efficiently.

    Lets first refresh what is a median

    • The median is the middle element in the sorted list
    • Given a list of numbers
    `
    The median is the middle element in the sorted list.
    
    Given
    13, 23, 11, 16, 15, 10, 26
    
    Sort them
    10, 11, 13, 15, 16, 23, 26
             Median
    
    If we have an even number of elements we average
    
    E.g.
    10, 11, 13, 15, 16, 23, 26, 32
                    /
                 15.5

    They way we solve the problem is by using two heaps (Low & High) to divide the array into tow parts.

                            Low                 |                      High

                         Max Heap          |                    Min Heap

    Low part is a max heap, high part is a min heap.

    `
    (n/2 ± 1) smallest items in a low MaxHeap       (n/2 ± 1) biggest items in a high MinHeap
    
            peek => n/2th smallest                     peek => n/2th smallest
                                                       /
                                        MEDIAN!
    `

    If low part size is equals to high part size, then we get avg value, otherwise, we get from larger size heap.

    function MedianMaintaince() {
      let lowMaxHeap = new Heap((b, a) => a - b);
      let highMinHeap = new Heap((a, b) => a - b);
    
      return {
        add(value) {
          // For the first element, we add to lowMaxHeap by default
          if (lowMaxHeap.size() === 0 || value < lowMaxHeap.peek()) {
            lowMaxHeap.add(value);
          } else {
            highMinHeap.add(value);
          }
    
          /**
           * Reblance:
           *
           * If low.size = 2; high.size = 4, then we move the root of high to the low part
           * so that low.size = 3, high.size = 3
           */
          let smallerHeap =
            lowMaxHeap.size() > highMinHeap.size() ? highMinHeap : lowMaxHeap;
          let biggerHeap = smallerHeap === lowMaxHeap ? highMinHeap : lowMaxHeap;
          if (biggerHeap.size() - smallerHeap.size() > 1) {
            smallerHeap.add(biggerHeap.extractRoot());
          }
    
          /**
           * If low.szie === high.size, extract root for both and calculate the average value
           */
          if (lowMaxHeap.size() === highMinHeap.size()) {
            return (lowMaxHeap.peek() + highMinHeap.peek()) / 2;
          } else {
            // get peak value from the bigger size of heap
            return lowMaxHeap.size() > highMinHeap.size()
              ? lowMaxHeap.peek()
              : highMinHeap.peek();
          }
        }
      };
    }
    
    const mm = new MedianMaintaince();
    console.log(mm.add(4)); // 4
    console.log(mm.add(2)); // 3
    console.log(mm.add(5)); // 4
    console.log(mm.add(3)); // 3.5

    We have heap data structure:

    function printArray(ary) {
      console.log(JSON.stringify(ary, null, 2));
    }
    
    function Heap(cmpFn = () => {}) {
      let data = [];
      return {
        data,
        // 2n+1
        leftInx(index) {
          return 2 * index + 1;
        },
        //2n + 2
        rightInx(index) {
          return 2 * index + 2;
        },
        // left: (n - 1) / 2, left index is always odd number
        // right: (n - 2) / 2, right index is always even number
        parentInx(index) {
          return index % 2 === 0 ? (index - 2) / 2 : (index - 1) / 2;
        },
        add(val) {
          this.data.push(val);
          this.siftUp(this.data.length - 1);
        },
        extractRoot() {
          if (this.data.length > 0) {
            const root = this.data[0];
            const last = this.data.pop();
            if (this.data.length > 0) {
              // move last element to the root
              this.data[0] = last;
              // move last elemment from top to bottom
              this.siftDown(0);
            }
    
            return root;
          }
        },
        siftUp(index) {
          // find parent index
          let parentInx = this.parentInx(index);
          // compare
          while (index > 0 && cmpFn(this.data[index], this.data[parentInx]) < 0) {
            //swap parent and current node value
            [this.data[index], this.data[parentInx]] = [
              this.data[parentInx],
              this.data[index]
            ];
            //swap index
            index = parentInx;
            //move to next parent
            parentInx = this.parentInx(index);
          }
        },
        siftDown(index) {
          const minIndex = (leftInx, rightInx) => {
            if (cmpFn(this.data[leftInx], this.data[rightInx]) <= 0) {
              return leftInx;
            } else {
              return rightInx;
            }
          };
          let min = minIndex(this.leftInx(index), this.rightInx(index));
          while (min >= 0 && cmpFn(this.data[index], this.data[min]) > 0) {
            [this.data[index], this.data[min]] = [this.data[min], this.data[index]];
            index = min;
            min = minIndex(this.leftInx(index), this.rightInx(index));
          }
        },
        peek() {
          return this.data[0];
        },
        print() {
          printArray(this.data);
        },
        size() {
          return this.data.length;
        }
      };
    }
    

      

  • 相关阅读:
    开源数据访问组件Smark.Data 1.8
    .NET应用加载容器KGlue
    TCP&UDP压力测试工具
    使用Beetle.Express简单构建高吞吐的TCP&UDP应用
    通过分析内存来优化.NET程序
    winsock I/O模型
    C++各大有名库的介绍
    深入研究 STL Deque 容器An InDepth Study of the STL Deque Container (By Nitron)
    C C++编程子资料库(小程序)
    VSS服务器安装配置(比较完整的一篇VSS服务器配置的文章)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10222226.html
Copyright © 2011-2022 走看看