算法打卡

2021-04-21  本文已影响0人  北暖37

四月第三周

1、


image.png
/**
 * @param {number[]} nums
 * @return {number}
 */
var findMin = function(nums) {
    let min = nums[0]
    let minIndex = 0
    for (let i = 0; i < nums.length; i++) {
        if (min > nums[i]) {
            min = nums[i]
            minIndex = i
        }
    }
    console.log(minIndex, '11111')
    return min
};
2、 image.png
/**
 * @param {number[]} nums
 * @return {number}
 */
var findPeakElement = function(nums) {
    if (nums.length === 1) return 0 
    let result = -1
    for( let i = 0 ; i < nums.length ; i++){
        if ( !i && nums[i] > nums[i+1]) {
            result = i
        } else if ( i === nums.length-1 && nums[i] > nums[i-1]) {
            result = i
        } else if ( nums[i] > nums[i-1] && nums[i] > nums[i+1]) {
            result = i
        }
    }
    return result
};

四月第四周

1、


3.png
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {TreeNode}
 */
var lowestCommonAncestor = function(root, p, q) {
  if (!root || root === p || root === q) return root;
  const left = lowestCommonAncestor(root.left, p, q);
  const right = lowestCommonAncestor(root.right, p, q);
  if (!left) return right; // 左子树找不到,返回右子树
  if (!right) return left; // 右子树找不到,返回左子树
  return root;
};

2、


4.png
/**
 * @param {number} capacity
 */
var LRUCache = function(capacity) {
    this.capacity = capacity;
    this.cache = new Map();
};

/** 
 * @param {number} key
 * @return {number}
 */
LRUCache.prototype.get = function(key) {
    if (this.cache.has(key)) {
        let value = this.cache.get(key) 
        this.cache.delete(key)
        this.cache.set(key, value)
        return value
    } else {
        return -1
    }
};

/** 
 * @param {number} key 
 * @param {number} value
 * @return {void}
 */
LRUCache.prototype.put = function(key, value) {
    this.cache.delete(key)
    this.cache.set(key, value)
    if (this.cache.size > this.capacity) {
        this.cache.delete(this.cache.keys().next().value)
    }
};

/**
 * Your LRUCache object will be instantiated and called as such:
 * var obj = new LRUCache(capacity)
 * var param_1 = obj.get(key)
 * obj.put(key,value)
 */
上一篇 下一篇

猜你喜欢

热点阅读