Leetcode刷题记录-js

Leetcode刷题记录

2019.08.01起每天至少写一道leetcode
字符串:125
数组:26 67 88 118 119 136
链表:21
树:100 101 107 108 110 112

0801
13. Roman to Integer Easy
思路: 创建一个Map对象存放罗马字母表。遍历字符串,第一个字母大于或第二个字母的话,做加法,小于做减法。

/**
 * @param {string} s
 * @return {number}
 */
var romanToInt = function(s) {
    if(!s||s.length === 0) return 0
    let map = new Map([['I',1],['V',5],['X',10],['L',50],['C',100],['D',500],['M',1000]]);
    let n = s.length - 1;
    let result = map.get(s[n])
    while(n > 0) {
        const cur = map.get(s[n])
        const pre = map.get(s[n - 1]) 
        if(pre < cur) {
            result -= pre
        } else {
            result += pre
        }
        n--
    }
    return result
}; 

0802
14.Longest Common Prefix Easy
思路:先排序,用第一个和最后一个元素split拆分遍历对比。

/**
 * @param {string[]} strs
 * @return {string}
 */
var longestCommonPrefix = function(strs) {
    
    if(strs==null) return '';
    if(strs.length == 0) return '';
    if(strs.length == 1) return strs[0];
    
    let list = strs.concat().sort();
    
    let list_first = list[0].split('');
    let list_last = list[list.length - 1].split('');
    let result = '';
    
    list_first.forEach((word,index) => {
        
        if (index!==result.length) return;
        
        if (list_first[index] == list_last[index]) {
            result += word;
        }
    })
    return result;
};

21.Merge Two Sorted Lists Easy
思路:就是一个很简单的链表题。

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var mergeTwoLists = function(l1, l2) {
    let preHead = new ListNode();
    let current = preHead;
    while (l1 && l2) {
        if (l1.val <= l2.val) {
            current.next = new ListNode(l1.val)
            l1 = l1.next
        } else {
            current.next = new ListNode(l2.val)
            l2 = l2.next
        }
        current = current.next;
    }
    current.next = l1 || l2;
    return preHead.next;
};

0803
26.Remove Duplicates from Sorted Array Easy
思路:数组去重问题。

/**
 * @param {number[]} nums
 * @return {number}
 */
var removeDuplicates = function(nums) {
    nums.forEach((item,index) => {
        while(item == nums[index + 1]) {
            nums.splice(index + 1, 1);
        }
    })
    return nums.length;
};

0804
27.Remove Element

/**
 * @param {number[]} nums
 * @param {number} val
 * @return {number}
 */
var removeElement = function(nums, val) {
    while(nums.indexOf(val,0) >= 0) {
        nums.splice(nums.indexOf(val,0), 1);
    }
    return nums.length;
};

0806
28.Implement strStr()

/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function(haystack, needle) {
    return haystack.indexOf(needle)
};

35.Search Insert Position

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var searchInsert = function(nums, target) {
    if(nums.indexOf(target) !== -1) { 
        return nums.indexOf(target)
    } else {
        for(let i = 0;i<=nums.length;i++){
            if(nums[i]>=target) {
                return i
            } else if(i==nums.length) {
                return i
            }
        }
    }
    
};

0827
53.Maximum Subarray

/**
 * @param {number[]} nums
 * @return {number}
 */
var maxSubArray = function(nums) {
    if(nums.length == 1) return nums[0]
    let res = nums[0]
    let currentSum = 0
    nums.forEach(item=>{
        currentSum = Math.max(item + currentSum,item)
        res = Math.max(currentSum, res)
    })
    return res
};

0828
58.Length of Last Word

需要注意的是字符串如果为空或者没有最后一个单词要返回零

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLastWord = function(s) {
    if(!s) return 0
    s = s.trim()
    let arr = s.split(" ")
    return arr[arr.length - 1].length
};

66.Plus One

注意当数字各个位都是9的时候的情况

/**
 * @param {number[]} digits
 * @return {number[]}
 */
var plusOne = function(digits) {
    for(let i = digits.length - 1; i >= 0; i--) {
        let current = digits[i] + 1
        
        if(current == 10){
            digits[i] = 0
        } else {
            ++digits[i]
            break
        }
        
        if(i==0&¤t==10) digits.unshift(1)
    }
    return digits
};

67.Add Binary

思路是先补零,然后从个位开始计算,注意进位问题

/**
 * @param {string} a
 * @param {string} b
 * @return {string}
 */
var addBinary = function(a, b) {
    let res = ''
    let aLen = a.length
    let bLen = b.length
    let carry = 0
    // 补零
    if(aLen > bLen){
        for(let i = 0 ; i < aLen - bLen; i++) {
            b = '0' + b
        }
    } else {
        for(let i = 0; i < bLen - aLen; i++) {
            a = '0' + a
        }
    }
    for(let i = Math.max(aLen,bLen) - 1; i>=0; i--) {
        let sum = Number(a[i]) + Number(b[i]) + carry
        res = String(sum % 2) + res
        carry = Math.floor(sum/2)
    }
    if(carry) {
        res = '1'+res
    }
    return res
};

88.Merge Sorted Array

先把两个数组合并成一个之后再排序,最后给nums1重新赋值

/**
 * @param {number[]} nums1
 * @param {number} m
 * @param {number[]} nums2
 * @param {number} n
 * @return {void} Do not return anything, modify nums1 in-place instead.
 */
var merge = function(nums1, m, nums2, n) {
    const num = nums1.splice(0, m).concat(nums2.splice(0,n))
    num.sort((a,b)=> a - b)
    num.forEach((_n,i)=> nums1[i]=_n)
    return nums1
};

树相关的题
100.Same Tree

判断两个二叉树是否相等,递归

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {boolean}
 */
var isSameTree = function(p, q) {
    if(!p && !q) return true
    if(!p || !q || p.val !== q.val) return false
    return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right)
};

101.Symmetric Tree

判断树是否对称,跟100题一样用递归,但是注意需要递归的对象

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var isSymmetric = function(root) {
    if(!root) return true
    function mirror(left,right) {
        if(!left && !right) return true
        if (!left || !right || left.val !== right.val) return false
        return mirror(left.left,right.right)&&mirror(left.right,right.left)
    }
    return mirror(root.left, root.right)
};

107.Binary Tree Level Order Traversal II

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrderBottom = function(root) {
    if(!root) return []
    let result = []
    let queue = [root]
    
    while(queue.length > 0) {
        let size = queue.length
        let current = []
        
        for (let i = 0; i < size; i++) {
            let head = queue.shift()
            current.push(head.val)
            if(head.left !== null) { queue.push(head.left) }
            if(head.right !== null) { queue.push(head.right) }
        }
        result.unshift(current)
    }
    
    return result
};

108.Convert Sorted Array to Binary Search Tree

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {number[]} nums
 * @return {TreeNode}
 */
var sortedArrayToBST = function(nums) {
    if(!nums.length) return null
    
    let half = Math.floor(nums.length / 2)
    let root = new TreeNode(nums[half])
    
    if(nums.slice(0,half).length>0){
        root.left = sortedArrayToBST(nums.slice(0,half))
    }
    if(nums.slice(half+1).length>0){
        root.right = sortedArrayToBST(nums.slice(half+1))
    }
    return root
};

0829
110.Balanced Binary Tree
平衡二叉树。左右子树的高度差不应超过1,平衡因子:1 0 -1(左正右负)

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var isBalanced = function(root) {
    if(root == null) return true
    
    let left = treeSize(root.left)
    let right = treeSize(root.right)
    let difference = Math.abs(right - left)
    let result = true
    
    if(difference>1) return false
    
    return result && isBalanced(root.left) && isBalanced(root.right)
};
var treeSize = function(root) {
    if(root == null) return 0
    return 1 + Math.max(treeSize(root.left),treeSize(root.right))
}

112.Path Sum
给一个树和一个和,看看有没有路径和等于这个和

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} sum
 * @return {boolean}
 */
var hasPathSum = function(root, sum) {
    if(root == null) return false
    if(root.left == null && root.right == null) return sum == root.val
    return hasPathSum(root.left,sum-root.val)||hasPathSum(root.right,sum-root.val)
};

118.Pascals Triangle
杨辉三角

  • 前两行是不变的[1][1,1]
  • k行有k个元素
  • 每行第一个和最后一个元素都是1
  • 对于第k(k > 2)行第n(n > 1 && n < k)个元素A[k][n],A[k][n] = A[k-1][n-1] + A[k-1][n]
/**
 * @param {number} numRows
 * @return {number[][]}
 */
function getRows (pre) {
    let currentRow = [1]
    for(let i = 0;i

119.Pascals Triangle II
思路同上,更换当前数组

/**
 * @param {number} rowIndex
 * @return {number[]}
 */
function currentRow(pre) {
    let row = [1]
    for(let i = 0;i

125.Vaild Palindrome
有效回文

/**
 * @param {string} s
 * @return {boolean}
 */
var isPalindrome = function(s) {
    s = s.replace(/[^0-9a-zA-Z]+/gmi,'')
    s = s.toLowerCase()
    let l = 0
    let r = s.length - 1
    
    while(l < r){
        if(s.charAt(l)!==s.charAt(r)) return false
        ++l
        --r
    }
    return true
};

136.Single Number

/**
 * @param {number[]} nums
 * @return {number}
 */
var singleNumber = function(nums) {
    for (let i = 0; i < nums.length; i++) {
        let current = nums.pop()
        if(nums.includes(current)){
            nums.unshift(current)
            continue;
        }
        return current
    }
};

你可能感兴趣的:(Leetcode刷题记录-js)