上班摸鱼刷了几道算法题

Posted усил

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了上班摸鱼刷了几道算法题相关的知识,希望对你有一定的参考价值。

118.杨辉三角

/*
 * @lc app=leetcode.cn id=118 lang=javascript
 *
 * [118] 杨辉三角
 */

// @lc code=start
/**
 * @param number numRows
 * @return number[][]
 */
var generate = function (numRows) 
    let res = [[1]];
    if (numRows) 
        for (let i = 1; i < numRows; i++)  
            res[i] = []; // 第i层
            for (let j = 0; j < i + 1; j++)  // 第 i 层 包含 (i + 1) 个
                 res[i][j] = (res[i - 1][j] || 0) + (res[i - 1][j - 1] || 0);
            
        
        return res;
     else 
        return [];
    
;
// @lc code=end

119.杨辉三角-ii

/*
 * @lc app=leetcode.cn id=119 lang=javascript
 *
 * [119] 杨辉三角 II
 */

// @lc code=start
/**
 * @param number rowIndex
 * @return number[]
 */
var getRow = function(rowIndex) 
    let res = [[1]];
    if (rowIndex) 
        for (let i = 1; i <= rowIndex; i++) 
             res[i] = [];
             for (let j = 0; j < i + 1; j++) 
                res[i][j] = (res[i - 1][j] || 0) + (res[i - 1][j - 1] || 0);
             
        
        return res[rowIndex];
     else 
        return res[0];
     
;
// @lc code=end

121.买卖股票的最佳时机

/*
 * @lc app=leetcode.cn id=121 lang=javascript
 *
 * [121] 买卖股票的最佳时机
 */

// @lc code=start
/**
 * @param number[] prices
 * @return number
 */
var maxProfit = function(prices) 
   // 最大利润
   let maxProfitVal = 0;
   // 价格最低
   let minPrice = prices[0];
   for (let i = 0; i < prices.length; i++) 
      if (prices[i] < minPrice) 
        // 更新最低价格
        minPrice = prices[i];
       else 
        // 计算最大利润
        maxProfitVal = Math.max(maxProfitVal, prices[i] - minPrice);
      
   
   return maxProfitVal;
;
console.log(maxProfit([7,1,5,3,6,4]));
console.log(maxProfit([7,6,4,3,1]));
// @lc code=end

125.验证回文串

/*
 * @lc app=leetcode.cn id=125 lang=javascript
 *
 * [125] 验证回文串
 */

// @lc code=start
/**
 * @param string s
 * @return boolean
 */
var isPalindrome = function (s) 
    s = s.replace(/[^a-z0-9A-Z]/g, '').toLowerCase();
    let left = 0;
    let right = s.length - 1;
    while(left < right) 
        if (s[left] != s[right]) 
            return false;
        
        left++;
        right--;
    
    return true;
   
;
// @lc code=end

136.只出现一次的数字

/*
 * @lc app=leetcode.cn id=136 lang=javascript
 *
 * [136] 只出现一次的数字
 */

// @lc code=start
/**
 * @param number[] nums
 * @return number
 */
var singleNumber = function (nums) 
    nums.sort((a, b) => a - b);
    let i = 0;
    while(i < nums.length) 
        if (nums[i] != nums[i + 1]) return nums[i];
        i += 2;
    
;
// @lc code=end

168.excel表列名称

/*
 * @lc app=leetcode.cn id=168 lang=javascript
 *
 * [168] Excel表列名称
 */

// @lc code=start
/**
 * @param number columnNumber
 * @return string
 */
var convertToTitle = function(columnNumber) 
    let str = '';
    columnNumber--; 

    if (columnNumber == 0) str = 'A';

    while(columnNumber > 0) 
        // 求余
        let temp = columnNumber % 26;
        // 更新行 (需减一),第一行对应 A
        columnNumber = Math.floor(columnNumber / 26) - 1;
        // 65 是 A
        // 注:计算出来的字符串是添加在之前字符串的前面
        str = String.fromCharCode(temp + 65) + str;
        if (columnNumber == 0) str = "A" + str;
    
    return str;
;
// console.log(convertToTitle(1));
// console.log(convertToTitle(28));
// console.log(convertToTitle(701));
// console.log(convertToTitle(2147483647));
// @lc code=end

169.多数元素

/*
 * @lc app=leetcode.cn id=169 lang=javascript
 *
 * [169] 多数元素
 */

// @lc code=start
/**
 * @param number[] nums
 * @return number
 */
var majorityElement = function(nums) 
    const len = nums.length;
    const count = Math.floor(len / 2);
    nums.sort((a, b) => a - b);

    
;
// @lc code=end

171.excel-表列序号

/*
 * @lc app=leetcode.cn id=171 lang=javascript
 *
 * [171] Excel 表列序号
 */

// @lc code=start
/**
 * @param string columnTitle
 * @return number
 */
var titleToNumber = function(columnTitle) 
    let number = 0;
    // 进制
    let multiple = 1;
    let len = columnTitle.length;
    for(let i = len - 1; i >= 0; i--) 
        let k = columnTitle.charAt(i).charCodeAt() - 65 + 1;
        number += k * multiple;
        // 从右往左每前进一位进制需要乘上 26
        multiple *= 26;
    
    return number;
;
// console.log(titleToNumber('AB'));
// console.log(titleToNumber('ZY'));
// @lc code=end

219.存在重复元素-ii

/*
 * @lc app=leetcode.cn id=219 lang=javascript
 *
 * [219] 存在重复元素 II
 */

// @lc code=start
/**
 * @param number[] nums
 * @param number k
 * @return boolean
 */
var containsNearbyDuplicate = function(nums, k) 
     
;
// @lc code=end

231.2-的幂

/*
 * @lc app=leetcode.cn id=231 lang=javascript
 *
 * [231] 2 的幂
 */

// @lc code=start
/**
 * @param number n
 * @return boolean
 */
var isPowerOfTwo = function(n) 
    if (n <= 0) return false;
    
    let sum = 0;
    for (let i = 0; i < 32; i++) 
        sum += ((n >> i) & 1);
    

    if (sum == 1) return true;

    return false;
;
// @lc code=end

389.找不同

/*
 * @lc app=leetcode.cn id=389 lang=javascript
 *
 * [389] 找不同
 */

// @lc code=start
/**
 * @param string s
 * @param string t
 * @return character
 */
var findTheDifference = function(s, t) 
    let res;
    let arr = new Array(26).fill(0);

    // 计算 26个字符串出现的次数
    s.split("").forEach(item => 
       arr[item.charCodeAt() - 'a'.charCodeAt()]++;
    );

    t.split("").forEach(item => 
       arr[item.charCodeAt() - 'a'.charCodeAt()]--;
       if (arr[item.charCodeAt() - 'a'.charCodeAt()] < 0) 
            res = item;
       
    ); 

    return res;
;
// let s = "ymbgaraibkfmvocpizdydugvalagaivdbfsfbepeyccqfepzvtpyxtbadkhmwmoswrcxnargtlswqemafandgkmydtimuzvjwxvlfwlhvkrgcsithaqlcvrihrwqkpjdhgfgreqoxzfvhjzojhghfwbvpfzectwwhexthbsndovxejsntmjihchaotbgcysfdaojkjldprwyrnischrgmtvjcorypvopfmegizfkvudubnejzfqffvgdoxohuinkyygbdzmshvyqyhsozwvlhevfepdvafgkqpkmcsikfyxczcovrmwqxxbnhfzcjjcpgzjjfateajnnvlbwhyppdleahgaypxidkpwmfqwqyofwdqgxhjaxvyrzupfwesmxbjszolgwqvfiozofncbohduqgiswuiyddmwlwubetyaummenkdfptjczxemryuotrrymrfdxtrebpbjtpnuhsbnovhectpjhfhahbqrfbyxggobsweefcwxpqsspyssrmdhuelkkvyjxswjwofngpwfxvknkjviiavorwyfzlnktmfwxkvwkrwdcxjfzikdyswsuxegmhtnxjraqrdchaauazfhtklxsksbhwgjphgbasfnlwqwukprgvihntsyymdrfovaszjywuqygpvjtvlsvvqbvzsmgweiayhlubnbsitvfxawhfmfiatxvqrcwjshvovxknnxnyyfexqycrlyksderlqarqhkxyaqwlwoqcribumrqjtelhwdvaiysgjlvksrfvjlcaiwrirtkkxbwgicyhvakxgdjwnwmubkiazdjkfmotglclqndqjxethoutvjchjbkoasnnfbgrnycucfpeovruguzumgmgddqwjgdvaujhyqsqtoexmnfuluaqbxoofvotvfoiexbnprrxptchmlctzgqtkivsilwgwgvpidpvasurraqfkcmxhdapjrlrnkbklwkrvoaziznlpor";
// let t = "qhxepbshlrhoecdaodgpousbzfcqjxulatciapuftffahhlmxbufgjuxstfjvljybfxnenlacmjqoymvamphpxnolwijwcecgwbcjhgdybfffwoygikvoecdggplfohemfypxfsvdrseyhmvkoovxhdvoavsqqbrsqrkqhbtmgwaurgisloqjixfwfvwtszcxwktkwesaxsmhsvlitegrlzkvfqoiiwxbzskzoewbkxtphapavbyvhzvgrrfriddnsrftfowhdanvhjvurhljmpxvpddxmzfgwwpkjrfgqptrmumoemhfpojnxzwlrxkcafvbhlwrapubhveattfifsmiounhqusvhywnxhwrgamgnesxmzliyzisqrwvkiyderyotxhwspqrrkeczjysfujvovsfcfouykcqyjoobfdgnlswfzjmyucaxuaslzwfnetekymrwbvponiaojdqnbmboldvvitamntwnyaeppjaohwkrisrlrgwcjqqgxeqerjrbapfzurcwxhcwzugcgnirkkrxdthtbmdqgvqxilllrsbwjhwqszrjtzyetwubdrlyakzxcveufvhqugyawvkivwonvmrgnchkzdysngqdibhkyboyftxcvvjoggecjsajbuqkjjxfvynrjsnvtfvgpgveycxidhhfauvjovmnbqgoxsafknluyimkczykwdgvqwlvvgdmufxdypwnajkncoynqticfetcdafvtqszuwfmrdggifokwmkgzuxnhncmnsstffqpqbplypapctctfhqpihavligbrutxmmygiyaklqtakdidvnvrjfteazeqmbgklrgrorudayokxptswwkcircwuhcavhdparjfkjypkyxhbgwxbkvpvrtzjaetahmxevmkhdfyidhrdeejapfbafwmdqjqszwnwzgclitdhlnkaiyldwkwwzvhyorgbysyjbxsspnjdewjxbhpsvj"
// console.log(findTheDifference(s, t));
// @lc code=end

392.判断子序列

/*
 * @lc app=leetcode.cn id=392 lang=javascript
 *
 * [392] 判断子序列
 */

// @lc code=start
/**
 * @param string s
 * @param string t
 * @return boolean
 */
var isSubsequence = function(s, t) 
    let len1 = s.length;
    let len2 = t.length;
    if (len1 > len2) return false;

    /**
     *  s = abc; t = ahbgdc;
     *  [
     *    [0, 0, 0, 0, 0, 0],
     *    [0, 0, 0, 0, 0, 0],
     *    [0, 0, 0, 0, 0, 0],
     *    [0, 0, 0, 0, 0, 0],
     *  ]
     */
    let dp = new Array(len1 + 1).fill(0).map(() => Array(len2 + 1).fill(0));
    
    for (let i = 1; i <= len1; i++) 
        for (let j = 1; j <= len2; j++) 
            if (s[i - 1] == t[j - 1]) 
                dp[i][j] = dp[i - 1][j - 1] + 1;
             else 
                dp[i][j] = dp[i][j - 1];
            
        
    
    return dp[len1][len2] === len1;
;
isSubsequence("abc", "ahbgdc");
// @lc code=end

以上是关于上班摸鱼刷了几道算法题的主要内容,如果未能解决你的问题,请参考以下文章

刷了 1000 多道算法题,一点心得

二叉树算法总结

解决四种二叉树遍历问题

上班在群里摸鱼,逮到一个字节8年测试开发,聊过之后羞愧难当...

几大排序思想(由javascript编写)

字节面试必须拿下的十道算法题,你会几道?