小S的倒排索引 | 豆包MarsCode AI刷题

47 阅读3分钟

解题思路

  1. 数组有序性:输入数组 ab 是按从小到大的顺序排列的,因此可以利用双指针法进行高效遍历。

  2. 双指针法

    • 定义两个指针分别指向数组 ab 的末尾。

    • 比较两个指针指向的元素:

      • 如果相等,说明该元素是交集,加入结果列表,并移动两个指针。
      • 如果 a 的当前值大于 b 的当前值,则移动指针 a
      • 如果 b 的当前值大于 a 的当前值,则移动指针 b
    • 重复上述过程,直到任一指针越界。

  3. 结果处理

    • 因为是从大到小顺序输出,直接从末尾开始构建结果列表即可。

算法实现

python
复制代码
def inverted_index_intersection(a, b):
    # 定义两个指针
    i, j = len(a) - 1, len(b) - 1
    result = []

    # 双指针查找交集
    while i >= 0 and j >= 0:
        if a[i] == b[j]:
            result.append(a[i])
            i -= 1
            j -= 1
        elif a[i] > b[j]:
            i -= 1
        else:
            j -= 1

    return result

# 测试样例
print(inverted_index_intersection([1, 2, 3, 7], [2, 5, 7]))  # 输出:[7, 2]
print(inverted_index_intersection([1, 4, 8, 10], [2, 4, 8, 10]))  # 输出:[10, 8, 4]
print(inverted_index_intersection([3, 5, 9], [1, 4, 6]))  # 输出:[]
print(inverted_index_intersection([1, 2, 3], [1, 2, 3]))  # 输出:[3, 2, 1]

复杂度分析

  1. 时间复杂度

    • 双指针法的时间复杂度为 O(m + n),其中 mn 分别为数组 ab 的长度。
    • 每个元素最多被访问一次。
  2. 空间复杂度

    • 结果列表的空间复杂度为 O(k),其中 k 是交集的大小。

解题思路

  1. 数组有序性:输入数组 ab 是按从小到大的顺序排列的,因此可以利用双指针法进行高效遍历。

  2. 双指针法

    • 定义两个指针分别指向数组 ab 的末尾。

    • 比较两个指针指向的元素:

      • 如果相等,说明该元素是交集,加入结果列表,并移动两个指针。
      • 如果 a 的当前值大于 b 的当前值,则移动指针 a
      • 如果 b 的当前值大于 a 的当前值,则移动指针 b
    • 重复上述过程,直到任一指针越界。

  3. 结果处理

    • 因为是从大到小顺序输出,直接从末尾开始构建结果列表即可。

算法实现

python
复制代码
def inverted_index_intersection(a, b):
    # 定义两个指针
    i, j = len(a) - 1, len(b) - 1
    result = []

    # 双指针查找交集
    while i >= 0 and j >= 0:
        if a[i] == b[j]:
            result.append(a[i])
            i -= 1
            j -= 1
        elif a[i] > b[j]:
            i -= 1
        else:
            j -= 1

    return result

# 测试样例
print(inverted_index_intersection([1, 2, 3, 7], [2, 5, 7]))  # 输出:[7, 2]
print(inverted_index_intersection([1, 4, 8, 10], [2, 4, 8, 10]))  # 输出:[10, 8, 4]
print(inverted_index_intersection([3, 5, 9], [1, 4, 6]))  # 输出:[]
print(inverted_index_intersection([1, 2, 3], [1, 2, 3]))  # 输出:[3, 2, 1]

复杂度分析

  1. 时间复杂度

    • 双指针法的时间复杂度为 O(m + n),其中 mn 分别为数组 ab 的长度。
    • 每个元素最多被访问一次。
  2. 空间复杂度

    • 结果列表的空间复杂度为 O(k),其中 k 是交集的大小。