数组
lc26 删除重复项
function removeDuplicates(nums: number[]): number {
let index = 0
for (let i = 0; i < nums.length; i++) {
if (i === 0 || nums[i - 1] !== nums[i]) {
nums[index] = nums[i]
index++
}
}
return index
};
lc283 移动零
function moveZeroes(nums: number[]): void {
let index = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== 0) {
nums[index] = nums[i]
index++
}
}
for (let i = index; i < nums.length; i++) {
nums[i] = 0
}
};
lc88 合并两个有序数组
function merge(nums1: number[], m: number, nums2: number[], n: number): void {
let i = m - 1;
let j = n - 1;
for (let k = m + n - 1; k >= 0; k--) {
if (j < 0 || (i >= 0 && nums1[i] > nums2[j])) {
nums1[k] = nums1[i]
i--
} else {
nums1[k] = nums2[j]
j--
}
}
};
链表
lc206 反转链表
function reverseList(head: ListNode | null): ListNode | null {
let last = null
while (head) {
const next = head.next
head.next = last
last = head
head = next
}
return last
};
lc25 k个一组反转链表
邻值查找(hard)
lc141 环形链表
function hasCycle(head: ListNode | null): boolean {
let fast = head
while (fast && fast.next) {
fast = fast.next.next
head = head.next
if (fast === head) return true
}
return false
};
lc142 环形链表Ⅱ
homework
lc21 合并两个有序链表
lc66 加一