算法学习记录(六十四)

85 阅读1分钟

问:

  1. 剑指 Offer 11. 旋转数组的最小数字
  2. 剑指 Offer 52. 两个链表的第一个公共节点
  3. 剑指 Offer 53 - I. 在排序数组中查找数字 I 解:
const minArray = function(arr) {
    let left = 0
    let right = arr.length - 1
    while (left < right) {
        const mid = Math.floor((left + right) >> 1)
        const target = arr[right]
        if (target < arr[mid]) {
            left = mid + 1
        } else if (target === arr[mid]) {
            right--   
        } else {
            right = mid
        }
    }
    return arr[left]
};
const getIntersectionNode = function(headA, headB) {
    let node1 = headA
    let node2 = headB
    let len1 = 0
    let len2 = 0
    while (node1) {
        len1++
        node1 = node1.next
    }
    while (node2) {
        len2++
        node2 = node2.next
    }
    let more = Math.abs(len1 - len2)
    node1 = headA
    node2 = headB
    while (more) {
        len1 > len2 ? node1 = node1.next : node2 = node2.next
        more--
    }
    while (node1 !== node2) {
        node1 = node1.next 
        node2 = node2.next 
    }
    return node1
};
const search = function(nums, target) {
    const idx1 = search(true)
    const idx2 = search(false)
    return idx2 - idx1 - 1

    function search(type) {
        let left = 0
        let right = nums.length - 1
        // type1: 找小于target最右的位置
        // type2: 找大于target最左的位置
        let res = type ? -1 : nums.length
        while (left <= right) {
            const mid = Math.floor((left + right) >> 1)
            if (type) {
                if (nums[mid] >= target) {
                    right = mid - 1
                } else {
                    left = mid + 1
                    res = mid
                }
            } else {
                if (nums[mid] <= target) {
                    left = mid + 1
                } else {
                    right = mid - 1
                    res = mid
                }
            }
        }
        return res
    }
};