likes
comments
collection
share

30 天刷题计划(四)

作者站长头像
站长
· 阅读数 36

题目来源: LeetCode 75 30 天 JavaScript 挑战

334. 递增的三元子序列

思路

遍历数组找到3个不连续的递增数字

代码

function increasingTriplet(nums: number[]): boolean {

  let first = nums[0]
  let second = null

  for(let i = 1; i < nums.length; i++) {
    if (second !== null && second < nums[i]) {
      return true
    }
    if(first < nums[i]) {
      second = nums[i]
    } else {
      first = nums[i]
    }
  }

  return false
};

443. 压缩字符串

思路

双指针解法,一个控制读取的位置 一个控制写入

代码

function compress(chars: string[]): number {
  let n = chars.length
  let read = 0
  let write = 0

  while(read < n) {
    let cnt = 0
    let cur = chars[read]

    while(read < n && chars[read] === cur) {
      cnt++
      read++
    }

    chars[write] = cur
    write++

    if (cnt !== 1) {
      let counter = (cnt + '').split('')

      counter.forEach(c => {
        chars[write++] = c
      })
    }
  }
  
  return write
};

283. 移动零

思路

双指针, 遇 0 交换

代码

/**
 Do not return anything, modify nums in-place instead.
 */
function moveZeroes(nums: number[]): void {
  let i = 0
  let j = 0

  for (; i < nums.length; i++) {
    if (nums[i] !== 0) {
      let temp = nums[i]
      nums[i] = nums[j]
      nums[j++] = temp
    }
  }
};

2665. 计数器 II

思路

闭包的使用

代码

type ReturnObj = {
    increment: () => number,
    decrement: () => number,
    reset: () => number,
}

function createCounter(init: number): ReturnObj {
   const _init = init
  
   return {
     increment: () => init += 1,
     decrement: () => init -= 1,
     reset: () => {
       init = _init
       return init
     }
   }
};

/**
 * const counter = createCounter(5)
 * counter.increment(); // 6
 * counter.reset(); // 5
 * counter.decrement(); // 4
 */

392. 判断子序列

思路

双指针, 如果 s 字符串的指针能走完即为子序列

代码

function isSubsequence(s: string, t: string): boolean {
  if(!s) {
    return true
  }

  for(let i = 0, j = 0; j < t.length; j++) {
    if (s[i] === t[j]) {
      i++
      if (i === s.length) {
        return true
      }
    }
  }
  return false
};
转载自:https://juejin.cn/post/7284143489738194984
评论
请登录