tìm tất cả cặp tổng k

Benchmark publishedon

Setup

const N = 5000;
const k = 10000;

// random array
const arr = Array.from({ length: N }, () => Math.floor(Math.random() * 10000));

// ==== Doubly Linked List ====
class Node {
  constructor(val) {
    this.val = val;
    this.next = null;
    this.prev = null;
  }
}

class DoublyLinkedList {
  constructor() {
    this.head = null;
    this.tail = null;
  }

  append(val) {
    const node = new Node(val);
    if (!this.head) {
      this.head = this.tail = node;
      return;
    }
    this.tail.next = node;
    node.prev = this.tail;
    this.tail = node;
  }
}

const dll = new DoublyLinkedList();
arr.forEach(v => dll.append(v));

function split(head) {
  let slow = head, fast = head;
  while (fast.next && fast.next.next) {
    slow = slow.next;
    fast = fast.next.next;
  }
  let second = slow.next;
  slow.next = null;
  if (second) second.prev = null;
  return second;
}

function merge(a, b) {
  if (!a) return b;
  if (!b) return a;

  if (a.val < b.val) {
    a.next = merge(a.next, b);
    if (a.next) a.next.prev = a;
    a.prev = null;
    return a;
  } else {
    b.next = merge(a, b.next);
    if (b.next) b.next.prev = b;
    b.prev = null;
    return b;
  }
}

function mergeSort(head) {
  if (!head || !head.next) return head;
  let second = split(head);
  head = mergeSort(head);
  second = mergeSort(second);
  return merge(head, second);
}

Test Runner

Initializing...

Testing in
Test CaseOps/sec
arr
const a = [...arr].sort((x, y) => x - y);
let l = 0, r = a.length - 1;
let count = 0;

while (l < r) {
  const sum = a[l] + a[r];
  if (sum === k) {
    count++;
    l++; r--;
  } else if (sum < k) {
    l++;
  } else {
    r--;
  }
}
ready
double llist
let sortedHead = mergeSort(dll.head);

// tìm tail
let tail = sortedHead;
while (tail.next) tail = tail.next;

let left = sortedHead;
let right = tail;
let count = 0;

while (left !== right && right.next !== left) {
  const sum = left.val + right.val;

  if (sum === k) {
    count++;
    left = left.next;
    right = right.prev;
  } else if (sum < k) {
    left = left.next;
  } else {
    right = right.prev;
  }
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

Revision 1
publishedon