leetcode简单(数组、字符串):[219, 268, 349, 414, 485, 541, 557, 821, 925, 977]

219. 存在重复元素

var containsNearbyDuplicate = function(nums, k) {
    for (let i = 0; i < nums.length; i++) {
        let j = nums.indexOf(nums[i], i + 1)
        if (j > -1 && Math.abs(i - j) <= k) {
            return true
        }
    }
    return false
};

268. 丢失的数字

var missingNumber = function(nums) {
    nums.sort((a, b) => a - b)
    for (let i = 0; i <= nums.length; i++) {
        if (i !== nums[i]) {
            return i
        }
    }
};

349. 两个数组的交集

var intersection = function(nums1, nums2) {
    let set1 = new Set(nums1)
    let set2 = new Set(nums2)
    return [...set1].filter(n => set2.has(n))
};

414. 第三大的数

var thirdMax = function(nums) {
    let newArr = Array.from(new Set(nums)).sort((a, b) => b - a)
    return newArr[2] || newArr[2] == 0 ? newArr[2] : newArr[0]
};

485. 最大连续 1 的个数

var findMaxConsecutiveOnes = function(nums) {
    let oneList = nums.join('').split('0').filter(i => i).map(i => i.length)
    return Math.max(...oneList) | 0

};

541. 反转字符串 II

var reverseStr = function(s, k) {
    let tmpK = []
    let result = []
    for (let i = 0; i < s.length; i++) {
        tmpK.push(s[i])
        if (tmpK.length == k || (tmpK.length < k && i == s.length - 1)) {
            tmpK = tmpK.reverse()
        }
        if (tmpK.length == k * 2 || i == s.length - 1) {
            result = result.concat(tmpK)
            tmpK = []
        }
    }
    return result.join('')
};

557. 反转字符串中的单词 III

var reverseWords = function(s) {
    var arr = s.split(' ')
    var result = []
    for (let i = 0; i < arr.length; i++) {
        result.push(arr[i].split('').reverse().join(''))
    }
    return result.join(' ')

};

821. 字符的最短距离

var shortestToChar = function(s, c) {
    let res = new Array(s.length).fill(s.length)
    for (let i = 0; i < s.length; i++) {
        if (s[i] == c) {
            for (let j = 0; j < s.length; j++) {
                res[j] = Math.min(Math.abs(i - j), res[j])
            }
        }
    }
    return res
};

925. 长按键入

var isLongPressedName = function(name, typed) {
    let reg = /([a-z])\1*/g
    let arr1 = name.match(reg)
    let arr2 = typed.match(reg)
    if (arr1.length !== arr2.length) return false
    for (let i = 0; i < arr1.length; i++) {
        if (arr1[i].length > arr2[i].length || arr1[i][0] !== arr2[i][0]) {
            return false
        }
    }
    return true
};

977. 有序数组的平方

var sortedSquares = function(nums) {
    let newArr = nums.map(n => Math.abs(n)).sort((a, b) => a - b)
    let res = newArr.map(n => n * n)
    return res
};
posted @ 2023-01-30 19:15  Echoyya、  阅读(26)  评论(0编辑  收藏  举报