算法题

106 阅读1分钟

1. 反转链表

function ReverseList(pHead)
{
   let pre = null,cur = pHead
   while(cur!=null) {
     let t = cur.next
     cur.next = pre
     pre = cur
     cur = t
   }
   return pre
}

2. 斐波拉洗

function jumpFloor(number)
{
  if(number === 1) return 1
  if(number === 2) return 2
  let dp = []
  dp[1] = 1
  dp[2] = 2
  for(let i = 3; i <= number; i++) {
    dp[i] = dp[i-1]+dp[i-2]
  }
  return dp[number]
}

3.  链表有环

function hasCycle( head ) {
   if(head == null || head.next == null) {
     return false
   }
   let fast = head;
   let low = head;
   while( fast!=null && fast.next != null){
     fast = fast.next.next;
     low = low.next;
     if(fast == low) {
       return true
     }
   }
   return false
}

4. 版本号排序

arr.sort((a, b) => {
  let i = 0;
  const arr1 = a.split(".");
  const arr2 = b.split(".");

  while (true) {
    const s1 = arr1[i];
    const s2 = arr2[i];
    i++;
    if (s1 === undefined || s2 === undefined) {
      return arr2.length - arr1.length;
    }

    if (s1 === s2) continue;

    return s2 - s1;
  }
});
console.log(arr);

5.最长字符串

var lengthOfLongestSubstring = function (s) {
    let map = new Map();
    let i = -1
    let res = 0
    let n = s.length
    for (let j = 0; j < n; j++) {
        if (map.has(s[j])) {
            i = Math.max(i, map.get(s[j]))
        }
        res = Math.max(res, j - i)
        map.set(s[j], j)
    }
    return res
};

6. lru

class LRUCache {
  constructor(capacity) {
    this.secretKey = new Map();
    this.capacity = capacity;
  }
  get(key) {
    if (this.secretKey.has(key)) {
      let tempValue = this.secretKey.get(key);
      this.secretKey.delete(key);
      this.secretKey.set(key, tempValue);
      return tempValue;
    } else return -1;
  }
  put(key, value) {
    // key存在,仅修改值
    if (this.secretKey.has(key)) {
      this.secretKey.delete(key);
      this.secretKey.set(key, value);
    }
    // key不存在,cache未满
    else if (this.secretKey.size < this.capacity) {
      this.secretKey.set(key, value);
    }
    // 添加新key,删除旧key
    else {
      this.secretKey.set(key, value);
      // 删除map的第一个元素,即为最长未使用的
      this.secretKey.delete(this.secretKey.keys().next().value);
    }
  }
}

7. 大数相加

      function add(num1,num2){
        let maxLength = Math.max(num1.length,num2.lenght)
        num1 = num1.padStart(maxLength,0)
        num2 = num2.padStart(maxLength,0)
        let t = 0
        let f = 0
        let sum = ""
        for(let i = 0; i < maxLength; i++) {
          let t = parseInt(num1[i]) + parseInt(num2[i]) + f
          f = Math.floor(t/10)
          sum = t % 10 + sum
        }
        if(f!==0) {
          sum = '' + f + sum
        }
        return sum
      }

8. 快速排序

function quickSort(arr, i, j) {
  if(i < j) {
    let left = i; 
    let right = j;
    let pivot = arr[left];
    while(i < j) {
      while(arr[j] >= pivot && i < j) {  // 从后往前找比基准小的数
        j--;
      }
      while(arr[i] <= pivot && i < j) {  // 从前往后找比基准大的数
        i++;
      }
      swap(i,j,arr)
    }
    swap(j,left,arr)
    quickSort(arr, left, i-1);
    quickSort(arr, i+1, right);
    return arr;  }
   }
    function swap(i,j,arr) {
      let t  t = arr[i]
      arr[i] = arr[j]
      arr[j] = t
     }
     // examplelet arr = [2, 10, 4, 1, 0, 9, 5 ,2];
     console.log(quickSort(arr, 0 , arr.length-1));

9. 归并

function merge(left, right) {
  let res = [];
  let i = 0;
  let j = 0;
  while (i < left.length && j < right.length) {
    if (left[i] < right[j]) {
      res.push(left[i]);
      i++;
    } else {
      res.push(right[j]);
      j++;
    }
  }
  if (i < left.length) {
    res.push(...left.slice(i));
  } else {
    res.push(...right.slice(j));  
}
  return res;
}
function mergeSort(arr) {
  if (arr.length < 2) {
    return arr; 
 }
  const mid = Math.floor(arr.length / 2); 
  const left = mergeSort(arr.slice(0, mid));
  const right = mergeSort(arr.slice(mid));
  return merge(left, right);
}
console.log(mergeSort([3, 6, 2, 4, 1]));

10. 冒泡排序

      function Sort(arr) {
        let n = arr.length - 1
        for(let i = 0; i < n; i++) {
         for(let j = 0; j < n - i - 1; j++) {
            if(arr[j] > arr[j+1]) {
              let t = arr[j]
              arr[j] = arr[j+1]
              arr[j+1] = t
            }
          } 
       } 
       return arr
      }
      console.log(Sort([3,2,1,5]))

11. 两数之和

var twoSum = function(nums, target) {
  let hash = []
  let ans = []
  for(let i = 0; i < nums.length; i++) {
    if(hash[target - nums[i]] !== undefined) {
      ans[0] = i
      ans[1] = hash[target - nums[i]]
      return ans
    }
    hash[nums[i]] = i  
}
};

12.连续子数组最大和

function FindGreatestSumOfSubArray(array)
{
   let sum = array[0]
   let ans = array[0]
   for(let i = 1; i < array.length ; i++) {
     if(sum > 0) {
       sum += array[i]
     } else {
       sum = array[i]
     }
     ans=Math.max(ans,sum)
   }
   return ans;
}

13. 最小路径和

var minPathSum = function(grid) {
    let row = grid.length, col = grid[0].length
    for(let i = 1; i < row; i++)
        grid[i][0] += grid[i - 1][0]
    for(let j = 1; j < col; j++)
        grid[0][j] += grid[0][j - 1]
    for(let i = 1; i < row; i++)
        for(let j = 1; j < col; j++)
            grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1])
    return grid[row - 1][col - 1]};

14全排列

var permute = function(nums) {
   let hash = []  let stack = []
   let ans = []  const dfs = () => {
    if(nums.length === stack.length) {
      ans.push(stack.slice(0))
      return
    }
    for(let i = 0; i < nums.length; i++) {
      if(hash[nums[i]] !== undefined) continue
      hash[nums[i]] = 1
      stack.push(nums[i])
      dfs()
      hash[nums[i]] = undefined
      stack.pop()
    }
  }
  dfs()
  return ans;
};

15. 层序遍历

利用一个栈取头和尾巴

var levelOrder = function(root) {
   let ans = []
   if(root === null)
   return ans;
   let stack = []
   stack.push(root)
   while(stack.length) {
   let cur = []
    let len = stack.length
    for(let i = 0; i < len; i++) {
      let q = stack.shift()
      cur.push(q.val)
      if(q.left!=null)
      stack.push(q.left)
      if(q.right!=null) stack.push(q.right)
    }
    ans.push(cur)
  }
  return ans;
};

16. 二叉树最大深度(leetcode104)

var maxDepth = function(root) {
  if(root === null) return 0
  let ans = 0  
  const dfs = (root,num) => {
    if(root.left === null && root.right === null){
      ans = Math.max(ans,num)
      return
    }
    if(root.left !== null) {
      dfs(root.left,num+1)
    }
    if(root.right !== null) {
      dfs(root.right,num+1)
    }
  }
  dfs(root,1)
  return ans
};

17. 链表交点(leetcode160)

var getIntersectionNode = function(headA, headB) {
  let t1 = headA  let t2 = headB  while(t1!=t2) {
    if(t1 === null) {
      t1 = headB    
    }else {
      t1 = t1.next
    }
     if(t2 === null) {
      t2 = headA
    } else {
      t2 = t2.next
    }
  }
  return t1
};

18. 删除重复子节点(leetcode83)

var deleteDuplicates = function(head) {
    if(head==null) return null;
    let pre=head;
    let cur=head.next;
    while(cur!=null){
      if(cur.val==pre.val){
        pre.next=cur.next;
        cur=cur.next;
      }
      else{
        pre=cur;
        cur=cur.next;
      }
    }
    return head;
   }