leetcode简单算法解析一

138 阅读2分钟

单链表反转

// 链表结构
function ListNode(val) {
    this.val = val;
    this.next = null;
}
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
let reverseList = function(head) {
    let node = head; 
    let pre = null;
    let next;
    while(node){
      next = node.next;
      node.next = pre;
      pre = node;
      node = next;
    }
    return pre;
};
使用迭代遍历整个链表,建立一个新的链表结构,遍历的时候新的使用当前节点的next属性指向前一个节点

两数之和

给定一个整数数组nums 和一个目标值target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
let twoSum = function(nums, target) {
    let arr = [];
    for (let i = 0, length = nums.length; i < length; i++) {
        let item = nums[i];
        if (arr.length > 0) {
            let index = arr.indexOf(target - item);
            if (index > -1) {
                return [nums.indexOf(arr[index]), i];
            } else {
               arr.push(item); 
            }
        } else {
          arr.push(item); 
        }
    };
};
使用一个新的数组存遍历的数据(存的是目标值 - 遍历出的数据),要是遍历的过程中数据存在与新数组中就是找到了

二叉树的最大深度

给定一个二叉树,找出其最大深度。二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。说明: 叶子节点是指没有子节点的节点。

// 数据结构
 function TreeNode(val) {
    this.val = val;
    this.left = this.right = null;
 }
/**
 * @param {TreeNode} root
 * @return {number}
 */
let maxDepth = function(root) {
    if (!root) {
        return 0
    };
    let count = Math.max(maxDepth(root.left), maxDepth(root.right));
    return count + 1;
};
使用递归得出每个节点的左右最深

只出现一次的数字

给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。

说明:你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗

/**
 * @param {number[]} nums
 * @return {number}
 */
let singleNumber = function(nums) {
    let num = 0;
    for (let i = 0, length = nums.length; i < length; i++) { 
        num = num ^ nums[i]
        console.log(num);
    }
    return num;
};
运用到了相同的数异或等于0,0异或任何数等于任何数