30 天刷题计划(四)
题目来源: LeetCode 75 30 天 JavaScript 挑战
思路
遍历数组找到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
};
思路
双指针解法,一个控制读取的位置 一个控制写入
代码
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
};
思路
双指针, 遇 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
}
}
};
思路
闭包的使用
代码
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
*/
思路
双指针, 如果 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