Home  >  Article  >  Web Front-end  >  Several common algorithms implemented in JS

Several common algorithms implemented in JS

高洛峰
高洛峰Original
2016-12-07 10:03:21857browse

(1) Array deduplication

Principle: define an object obj, and then use the array element as the attribute name of obj, and use whether the attribute name is repeated to determine the duplication

var unique = function(arr){
  let obj = {};
  let newArr = [];
  arr.forEach(function(x){
    if(!obj[x]){ //如果对象中没有该元素对应的属性
      obj[x] = true;
      newArr.push(x);
    }
  });
  return newArr;
}


(2) Use the quick sort algorithm to Array sorting

This includes two effects, one is to use the characteristics of quick sort to achieve quick sorting without deduplication, and the other is quick sorting without deduplication.

Principle: Obtain the target array, select an element as the flag, traverse the remaining elements, put them on the right if they are larger than the flag, and put them on the left if they are smaller than the flag.

Special note: There are elements equal to the flag bit. If you store equal elements, deduplication will be achieved. If you store them, they will not be deduplicated.

var quickSort = function(arr){
  if(arr.length <= 1){
    return arr;
  }
  //定义一个左数组,定义一个右数组
  let leftArr = [];
  let rightArr = [];
  //选定一个参照值
  let tag = arr[0];
  /*
   * 使用如下方式判断,会把重复元素去掉,就实现了快排的同时去重
   */
  for(let i = 0; i < arr.length; i++){
    if(arr[i] < tag){ //将比tag小的元素放在左数组中
      leftArr.push(arr[i]);
    }
    if(arr[i] > tag){ //将比tag大的元素放在右数组中
      rightArr.push(arr[i]);
    }
  }
  /*
   * 使用如下方式就是使用快排进行排序,不去重
   */
  for(let i = 1; i < arr.length; i++){
    if(arr[i] < tag){ //将比tag小的元素放在左数组中
      leftArr.push(arr[i]);
    }else{ //将比tag大的元素放在右数组中
      rightArr.push(arr[i]);
    }
  }
  //递归调用
  return [].concat(quickSort(leftArr),[tag],quickSort(rightArr));
}


(3) Count the characters that appear most frequently in the string

Principle: This is similar to array deduplication. It also uses an object obj to use the array element as the attribute name of the object. If the object does not exist, Attribute name, the value is assigned to 1, if it exists, the value is increased by 1.

var maxShowTimes = function(str){
  // 创建一个用于判重的对象
  let obj = {};
  // 判断字符串是否为空或只有一个元素
  if(str.length <= 1){
    return str.length === 0?&#39;字符串不能为空&#39;:str;
  }
  // 利用String的charAt()方法获取各个字符
  for(let i = 0; i <= str.length; i++){
    if(!obj[str.charAt(i)]){ //如果不存在
      obj[str.charAt(i)] = 1;
    }else{ //如果存在
      obj[str.charAt(i)] += 1;
    }
  }
  // 在obj对象中寻找值最大的那个属性
  let maxChar = &#39;&#39;;
  let maxTimes = 0;
  for(var k in obj){
    if(obj[k] > maxTimes){
      maxChar = k;
      maxTimes = obj[k];
    }
  }
  return maxChar;
}


(4) To achieve the exchange value of two variables without using the third variable

Principle: It is a variable substitution, the idea is very clever, and can only be used for the exchange of numbers.

var swap = function(a,b){
  if(a === b){
    return [a,b];
  }
  b = b - a; // 此处的 b - a中的b和a的值是最初的值
  a = a + b; // a = a + b -a; 实现了将b的值赋给a
  b = a - b; // b = a - (b - a) = 2a - b 相当于 2b = 2a;实现了将a的值赋给b
  return [a,b];
}


(5) Find the maximum difference of an array

Principle: traverse the array once, find the maximum and minimum values, and return the difference

var getMaxProfit = function(arr){
  // 定义两个变量,分别存贮最大值和最小值
  let maxNum = arr[0];
  let minNum = arr[0];
  for(let i = 0; i < arr.length; i++){
    if(arr[i] > maxNum){
      maxNum = arr[i];
    }
    if(arr[i] < minNum){
      minNum = arr[i];
    }
  }
  return maxNum - minNum;
}


(6) Get any length Principle of random string

: You can manually specify the character library and random character length n, and use the Math.floor() and Math.random() methods to obtain random characters.

var getRandomString = function(n){
  // 定义随机字符串的字符库
  let str = &#39;qwertyuiopasdfghjklzxcvbnm1234567890&#39;;
  // 定义一个临时变量tmp存储生成的随机字符串
  let tmp = &#39;&#39;;
  //获取str的长度
  let len = str.length;
  // 生成一个长度为n的随机字符串
  for(let i = 0; i < n; i++){
    tmp += str.charAt(Math.floor(Math.random() * len));
  }
  return tmp;
}



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn