js common algorithm summary

1. Determine whether a word is a palindrome?

Palindrome refers to changing the position or inverting the same vocabulary or sentence in the following text, resulting in the interest of looping back and forth. It is called palindrome, also called loopback. Such as mamam redivider .

When many people get such a topic, it is very easy to think of using for to reverse the alphabetical order of the string and then match it. In fact, the most important thing to examine is the realization of reverse. In fact, we can use ready-made functions to convert strings into arrays. This idea is very important, and we can have more degrees of freedom to perform string operations.

function checkPalindrom(str) {  
    return str == str.split('').reverse().join('');
}

2. Remove duplicate values ​​from a set of integer arrays

For example, input: [1,13,24,11,11,14,1,2], output: [1,13,24,11,14,2], need to remove the repeated elements 11 and 1.

It mainly examines the use of objects by individuals, and uses keys to filter.

let unique = function(arr) {  
  let hashTable = {};
  let data = [];
  for(let i=0,i<arr.length;i++) {
    if(!hashTable[arr[i]]) {
      hashTable[arr[i]] = true;
      data.push(arr[i]);
    }
  }
  return data

}

3. Count the letters with the most occurrences in a string

Given a continuous English string in English, find the letter with the most repeated occurrences

For example:  Input: afjghdfraaaasdenas Output: a

The previous heavy algorithm appeared in the past, here it is necessary to count the number of repetitions.

function findMaxDuplicateChar(str) {  
  if(str.length == 1) {
    return str;
  }
  let charObj = {};
  for(let i=0;i<str.length;i++) {
    if(!charObj[str.charAt(i)]) {
      charObj[str.charAt(i)] = 1;
    }else{
      charObj[str.charAt(i)] += 1;
    }
  }
  let maxChar = '',
      maxValue = 1;
  for(var k in charObj) {
    if(charObj[k] >= maxValue) {
      maxChar = k;
      maxValue = charObj[k];
    }
  }
  return maxChar;

}

4. Sorting algorithm

When it comes to algorithm topics, most of them should be relatively open topics, not limited to the implementation of algorithms, but it is necessary to master several of them, so bubble sorting, this relatively basic and easy-to-understand algorithm must be memorized in the heart. The bubble sorting algorithm is to compare the size in turn, and exchange the position of the small one and the big one.

function bubbleSort(arr) {  
    for(let i = 0,l=arr.length;i<l-1;i++) {
        for(let j = i+1;j<l;j++) { 
          if(arr[i]>arr[j]) {
                let tem = arr[i];
                arr[i] = arr[j];
                arr[j] = tem;
            }
        }
    }
    return arr;
}

Other sorts: quick sort

function quickSort(arr) {

    if(arr.length<=1) {
        return arr;
    }

    let leftArr = [];
    let rightArr = [];
    let q = arr[0];
    for(let i = 1,l=arr.length; i<l; i++) {
        if(arr[i]>q) {
            rightArr.push(arr[i]);
        }else{
            leftArr.push(arr[i]);
        }
    }

    return [].concat(quickSort(leftArr),[q],quickSort(rightArr));
}

5. Do not use temporary variables to exchange two integers

Example: input a = 2, b = 4 output a = 4, b =2

  This kind of problem is very ingenious, and requires everyone to jump out of the usual thinking and use a and b to replace it.

  Mainly use + - to perform operations, similar to a = a + ( b - a) is actually equivalent to the last a = b;

function swap(a , b) {  
  b = b - a;
  a = a + b;
  b = a - b;
  return [a,b];
}

Use canvas to draw a finite Fibonacci sequence curve?

The length of the sequence is limited to 9.

斐波那契数列, also known as the golden section sequence, refers to such a sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... In mathematics, the Fibonacci sequence mainly examines recursive calls . We generally know the definition

fibo[i] = fibo[i-1]+fibo[i-2];  

How to generate Fibonacci array

function getFibonacci(n) {  
  var fibarr = [];
  var i = 0;
  while(i<n) {
    if(i<=1) {
      fibarr.push(i);
    }else{
      fibarr.push(fibarr[i-1] + fibarr[i-2])
    }
    i++;
  }

  return fibarr;
}

The rest of the work is to use the canvas  arcmethod to draw the curve

7. Find the maximum difference of the following positive arrays

For example:  input [10,5,11,7,8,9] output 6

This is a question to test the search for the maximum value of a basic array. Obviously, we know that the maximum difference must be the difference between the maximum value and the minimum value in an array.

function getMaxProfit(arr) {

    var minPrice = arr[0];
    var maxProfit = 0;

    for (var i = 0; i < arr.length; i++) {
        var currentPrice = arr[i];

        minPrice = Math.min(minPrice, currentPrice);

        var potentialProfit = currentPrice - minPrice;

        maxProfit = Math.max(maxProfit, potentialProfit);
    }

    return maxProfit;
}

8. Randomly generate a string of specified length

Implement an algorithm to randomly generate characters of specified length.

For example: Given a length of 8, output 4ldkfg9j

function randomString(n) {  
  let str = 'abcdefghijklmnopqrstuvwxyz9876543210';
  let tmp = '',
      i = 0,
      l = str.length;
  for (i = 0; i < n; i++) {
    tmp += str.charAt(Math.floor(Math.random() * l));
  }
  return tmp;
}

9. Implement a function similar to getElementsByClassName

Implement a function by yourself to find all DOM nodes containing a certain class under a certain DOM node? It is not allowed to use natively provided DOM search functions such as getElementsByClassName querySelectorAll.

function queryClassName(node, name) {  
  var starts = '(^|[ \n\r\t\f])',
       ends = '([ \n\r\t\f]|$)';
  var array = [],
        regex = new RegExp(starts + name + ends),
        elements = node.getElementsByTagName("*"),
        length = elements.length,
        i = 0,
        element;

    while (i < length) {
        element = elements[i];
        if (regex.test(element.className)) {
            array.push(element);
        }

        i += 1;
    }

    return array;
}

10. Using JS to implement a binary search tree (Binary Search Tree)

Generally, the probability of writing it all is relatively small, but focus on your understanding of it and the realization of some basic features. Binary search tree, also known as binary search tree, ordered binary tree (English: ordered binary tree) refers to an empty tree or a binary tree with the following properties:

  • If the left subtree of any node is not empty, the values ​​of all nodes on the left subtree are less than the value of its root node;
  • If the right subtree of any node is not empty, the values ​​of all nodes on the right subtree are greater than the value of its root node;
  • The left and right subtrees of any node are also binary search trees;
  • There are no nodes with equal keys. The advantage of a binary search tree over other data structures is that the time complexity of searching and inserting is low. is O(log n). A binary search tree is a basic data structure used to build more abstract data structures, such as collections, multisets, associative arrays, etc.

 

  When writing, you need to fully understand the characteristics of the binary search tree, and you need to set the data structure of each node first

class Node {  
  constructor(data, left, right) {
    this.data = data;
    this.left = left;
    this.right = right;
  }
}

The tree is composed of nodes, which are gradually extended from the root node to each child node, so it has a basic structure that has a root node and methods for adding, searching and deleting nodes.

class BinarySearchTree {

  constructor() {
    this.root = null;
  }

  insert(data) {
    let n = new Node(data, null, null);
    if (!this.root) {
      return this.root = n;
    }
    let currentNode = this.root;
    let parent = null;
    while (1) {
      parent = currentNode;
      if (data < currentNode.data) {
        currentNode = currentNode.left;
        if (currentNode === null) {
          parent.left = n;
          break;
        }
      } else {
        currentNode = currentNode.right;
        if (currentNode === null) {
          parent.right = n;
          break;
        }
      }
    }
  }

  remove(data) {
    this.root = this.removeNode(this.root, data)
  }

  removeNode(node, data) {
    if (node == null) {
      return null;
    }

    if (data == node.data) {
      // no children node
      if (node.left == null && node.right == null) {
        return null;
      }
      if (node.left == null) {
        return node.right;
      }
      if (node.right == null) {
        return node.left;
      }

      let getSmallest = function(node) {
        if(node.left === null && node.right == null) {
          return node;
        }
        if(node.left != null) {
          return node.left;
        }
        if(node.right !== null) {
          return getSmallest(node.right);
        }

      }
      let temNode = getSmallest(node.right);
      node.data = temNode.data;
      node.right = this.removeNode(temNode.right,temNode.data);
      return node;

    } else if (data < node.data) {
      node.left = this.removeNode(node.left,data);
      return node;
    } else {
      node.right = this.removeNode(node.right,data);
      return node;
    }
  }

  find(data) {
    var current = this.root;
    while (current != null) {
      if (data == current.data) {
        break;
      }
      if (data < current.data) {
        current = current.left;
      } else {
        current = current.right
      }
    }
    return current.data;
  }

}

module.exports = BinarySearchTree;

Reprint address: https://www.jackpu.com/qian-duan-mian-shi-zhong-de-chang-jian-de-suan-fa-wen-ti/

Guess you like

Origin blog.csdn.net/guoweifeng0012/article/details/95078384