阅读 54

LeetCode第25天🐱‍🏍

162. 寻找峰值

var findPeakElement = function(nums) {
    let l = 0, r = nums.length - 1, res = 0 
    while (l <= r) {
        let mid = Math.floor((l + r) / 2)
        if (nums[mid - 1] < nums[mid] && nums[mid] > nums[mid + 1]) return mid
        if (nums[mid] > nums[mid + 1] && mid == 0) return 0
        if (nums[mid - 1] < nums[mid] && mid == nums.length - 1) return nums.length - 1
        if (nums[mid] < nums[mid + 1]) l = mid + 1
        else r = mid - 1
    }
    return res
};
复制代码

61. 旋转链表

QQ图片20210915170931.jpg

var rotateRight = function(head, k) {
    if (k === 0 || !head || !head.next) {
        return head;
    }
    let n = 1;
    let cur = head;
    while (cur.next) {
        cur = cur.next;
        n++;
    }

    let add = n - k % n;
    if (add === n) {
        return head;
    }

    cur.next = head;
    while (add) {
        cur = cur.next;
        add--;
    }

    const ret = cur.next;
    cur.next = null;
    return ret;
};
复制代码
文章分类
前端