数组去重:
function unique (arr){
var obj={};
var result=[];
arr.map(()=>{
if(!obj[item]){
obj[item]=true;
result.push(item)
}
})
return result;
}
阶乘
function factorialize(num) {
var result = 1;
if(num < 0)
return -1;
if(num == 0 || num == 1)
return 1;
while(num>1) {
result *= num--;
}
return result;
}
function factorialize(num) {
var result = 1;
if(num < 0)
return -1;
if(num == 0 || num == 1)
return 1;
if(num > 1)
return num*factorialize(num-1);
}
生成菲波那切数列
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;
}
let count = 0;
function fn(n) {
let cache = {};
function _fn(n) {
if (cache[n]) {
return cache[n];
}
count++;
if (n == 1 || n == 2) {
return 1;
}
let prev = _fn(n - 1);
cache[n - 1] = prev;
let next = _fn(n - 2);
cache[n - 2] = next;
return prev + next;
}
return _fn(n);
}
二分查找
function binary_search(arr, key) {
var low = 0,
high = arr.length - 1;
while(low <= high){
var mid = parseInt((high + low) / 2);
if(key == arr[mid]){
return mid;
}else if(key > arr[mid]){
low = mid + 1;
}else if(key < arr[mid]){
high = mid -1;
}
}
return -1;
}
实现栈的功能
定义一个栈
function Stack () {
this.dataStore = []; //初始化为空
this.top = 0; //记录栈顶位置
}
实现栈的pop,push
//元素入栈,栈顶位置加1
function push( ele ){
this.dataStore[this.top++] = ele;
}
//元素出栈,栈顶-1
function pop(){
return this.dataStore[--this.top];
}
实现链表的find,remove,add功能
定义一个链表
function Node(ele) {
this.element = ele; //当前节点的元素
this.next = null; //下一个节点链接
}
查找元素
function find ( item ) {
var currNode = this.head;
while ( currNode.element != item ){
currNode = currNode.next;
}
return currNode;
}
插入元素
function insert ( new , item ) {
var newNode = new Node( new );
var currNode = this.find( item );
newNode.next = currNode.next;
currNode.next = newNode;
}
删除元素
//找到删除元素的前一个节点
function findPrev( item ) {
var currNode = this.head;
while ( !( currNode.next == null) && ( currNode.next.element != item )){
currNode = currNode.next;
}
return currNode;
}
function remove ( item ) {
var prevNode = this.findPrev( item );
if( !( prevNode.next == null ) ){
prevNode.next = prevNode.next.next;
}
}
实现队列的in,out
定义队列
function Queue(){
var this.queue=[]
}
队尾in
function In(ele){
this.queue.push(ele)
}
队首out
function Out(){
this.queue.shift()
}