阅读 102

LeetCode第19天🐱‍🏍

11. 盛最多水的容器

双指针,数组第一项和最后一项为初始边界,当左边界小于右边界时,将下一次的左边界右移,反之右边界左移。

var maxArea = function(height) {
    let res = 0
    for(let i = 0, j = height.length - 1; i < j;) {
        const maxA = (j - i) * (height[i] < height[j] ? height[i++] : height[j--])  
        res = Math.max(res, maxA)
    }
    return res
};
复制代码

25. K 个一组翻转链表

const myReverse = (head, tail) => {
    let prev = tail.next;
    let p = head;
    while (prev !== tail) {
        const nex = p.next;
        p.next = prev;
        prev = p;
        p = nex;
    }
    return [tail, head];
}
var reverseKGroup = function(head, k) {
    const hair = new ListNode(0);
    hair.next = head;
    
    let pre = hair;

    while (head) {
        let tail = pre;
        // 查看剩余部分长度是否大于等于 k
        for (let i = 0; i < k; ++i) {
            tail = tail.next;
            if (!tail) {
                return hair.next;
            }
        }
        const nex = tail.next;
        [head, tail] = myReverse(head, tail);
        // 把子链表重新接回原链表
        pre.next = head;
        tail.next = nex;
        pre = tail;
        head = tail.next;
    }
    return hair.next;
};
复制代码
文章分类
前端