×

前端常见算法

96
_proto_麻瓜一袁
2017.07.13 11:17* 字数 124

判断是否是回文

function checkBack(str){
  return str==str.split("").reverse().join("");
}

console.log(checkBack("ava"));
console.log(checkBack("avaa"));

数组去重

function onlySet(arr){
  var res=[];
  arr.map(function(data){
    if(res.indexOf(data)===-1){
      res.push(data);
    }
  })
  return res;
}

console.log(onlySet([1,13,24,11,11,14,1,2]));

统计一个字符串出现最多的字母

function countMost(str){
  if(str.length===1) return str;
  var count=[];
  for(var i=0;i<str.length;i++){
    if(!count[str.charAt(i)]){
      count[str.charAt(i)]=1;
    }else{
      count[str.charAt(i)]++;
    }
  }
  var val="";
  var res="";
  for(var i in count){
    if(val==""){
      val=count[i];
      res=i;
    }else{
      if(val<count[i]){
        val=count[i];
        res=i;        
      }
    }
  }
  return res;
}


console.log(countMost("afjghdfraaaasdenas"));

引申为数组

排序算法 (冒泡,快速)

//不借助临时变量,进行两个整数的交换

//es6 
function swap(a,b){
  return [b,a];
}

console.log(swap(1,2));

//usually
function swap2(a,b){
  a=b+a; //想让一个等于总和
  b=a-b;
  a=a-b;
  return [a,b];
}

console.log(swap2(1,2));

生成斐波那契数组的方法

找出下列正数组的最大差值比如

function getMax(arr){
  return Math.max.apply(null,arr)-Math.min.apply(null,arr);
}

console.log(getMax([100,5,11,7,8,9]));

随机生成指定长度的字符串

function randomStr(n){
  var str="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
  var t="";
  for(var i=0;i<n;i++){
    t=str.charAt(Math.floor(Math.random()*str.length))+t;
  }
  return t;
}

console.log(randomStr(5));

//实现类似getElementsByClassName 的功能
function queryClassName(node,className){
  var reg=new RegExp('(^|\\s)'+className+'($|\\s)');
  var arr=[];
  var list=document.getElementsByTagName("*");
  for(var i = 0 ;i<list.length;i++){
    if(reg.test(className)){
      arr.push(list[i]);
    }
  }
  return arr;
}

二叉查找树

//在写的时候需要足够理解二叉搜素树的特点,需要先设定好每个节点的数据结构

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

}
//树是有节点构成,由根节点逐渐延生到各个子节点,因此它具备基本的结构就是具备一个根节点,具备添加,查找和删除节点的方法.

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;
  }

}

获取指定范围内的随机数

function getRandom(min,max){
  //return Math.floor(Math.random() * (max - min + 1)) + min;
  return min+Math.round(Math.random()*(max-min));
}

console.log(getRandom(0,10));

随机获取数组中的元素

function getRandomArr(arr){
  return arr[Math.floor(Math.random()*arr.length)];
}

console.log(getRandomArr([1,2,3]));

打乱数字数组的顺序

function shuffle(arr){
  return arr.sort(function(){
    return Math.random()-0.5;
  })
}
console.log(shuffle([1,2,3,4]));

保留指定小数位

var num =4.345678;
num = num.toFixed(4);
console.log(num);

折半

function binarySearch(des, arr) {
  if (!(arr instanceof Array))
    return "arr is not array";
  var low = 0;
  var high = arr.length;
  var mid;
  while (low <= high) {
    mid = Math.floor((low + high) / 2);
    if (arr[mid] < des) {
      low = mid + 1;
    } else if (arr[mid] > des) {
      high = mid - 1;
    } else {
      return mid;
    }
  }
  return 0;
}

冒泡

function bubbleSort(arr) {
  if (!(arr instanceof Array))
    return "arr is not array";
  var flag = true;
  for (var i = 0; i < arr.length - 1 && flag; i++) {
    flag = false;
    for (var j = arr.length - 1; j >= i; j--) {
      if (arr[j] < arr[j - 1]) {
        var temp = arr[j];
        arr[j] = arr[j - 1];
        arr[j - 1] = temp;
        flag = true;
      }
    }
  }
  return arr;
}

快排

function qsort(arr, low, high) {
  var pivot;
  if (low < high) {
    pivot = Partition(arr, low, high)
    this.qsort(arr, low, pivot - 1);
    this.qsort(arr, pivot + 1, high)
  }
}

function Partition(arr, low, high) {
  var pivotkey = arr[low];
  while (low < high) {
    while (low < high && arr[high] >= pivotkey)
      high--;
    swap(arr, low, high)
    while (low < high && arr[low] <= pivotkey)
      low++;
    swap(arr, low, high)
  }
  return low;
}

function quickSort(arr) {
  if (!(arr instanceof Array))
    return "arr is not array";
  this.qsort(arr, 0, arr.length - 1);
  return arr;
}

学习栈
Web note ad 1