算法与数据结构 / 62

双指针、哈希与多路合并练习

数据结构、边界条件与实现过程。 双指针、哈希与多路合并练习。

阅读说明: 保留原笔记的编号与章节顺序;代码只供查看,没有在本站运行。历史输出不代表当前版本的复现结果。截图/外链图以独立整理的公式、表格、示意或文字替换;纠错与必要补充均作说明。

  • binary search
    • 万金油 - while left < right - 1, 最后检查left和right
  • Basic sorting
    • bubble, selection, insert
    • time - O(n2)O(n^2), space - O(1)O(1)
  • Advanced sorting
    • merge sort
      • time - O(nlogn)O(nlogn), space - O(n)O(n)
    • quick sort
      • time - O(nlogn)O(nlogn), space - 平均O(logn)O(logn),最坏O(n)O(n)

结构选择速记: 链表关注指针重连;哈希表关注查找与计数;队列FIFO适合BFS;栈LIFO适合回头处理;BST保留有序关系;完全二叉堆可用数组索引,支持极值操作。具体复杂度由实现决定。

1. 2 sum

Determine if there exist two elements in a given array, the sum of which is the given target number.

Two Sum三种路线: 暴力枚举两下标O(n²);已排序数组首尾双指针O(n);未排序数组边扫描边查补数哈希集合,通常O(n)时间/O(n)空间。先查再加入,避免同一元素与自己配对。

PYTHON · 仅供阅读
# 边走边建立set,不能全部建立,因为(2+2=4)
class Solution(object):
    def existSum(self, array, target):
        """
        input: int[] array, int target
        return: boolean
        """
        # write your solution here
        result_set = set()
        for num in array:
            if target - num in result_set:
                return True
            else:
                result_set.add(num)

        return False

扩展约束: 明确输入是否有序、是否允许重复、返回存在性还是全部配对。超内存时可外部排序或按可恢复配对的规则分区,不能随意分桶后丢掉跨桶互补对;多机同样需要规划通信与倾斜。

2. 3 sum

Determine if there exist 3 elements in a given array, the sum of which is the given target number. Return all the triple of values that sums to target.

  • Time: 排序O(n2)O(n^2) + two sum O(n2)O(n^2) = O(n2)O(n^2)
  • Space: O(1)O(1)

整理注: 总时间O(n²)正确,但Python列表排序通常O(n log n),且可能使用O(n)临时空间;总空间还要计算返回的三元组。

PYTHON · 仅供阅读
class Solution(object):
    def allTriples(self, array, target):
        """
        input: int[] array, int target
        return: int[][]
        """
        # write your solution here
        result = []
        # option1 time: O(nlogn), space: O(n) - mergesort/ O(logn) - quicksort
        # option2 time: O(n^2), space: O(1) - bubble/selection/insertion
        array.sort()
        for i in range(len(array) - 2):
            '''
            Our goal is to find i < j < k, such that array[i] + array[j] + array[k] == target.
            To make sure there is no duplicate tuple, we ignore all the duplicate possible i.
            e.g, if we have 2, 2, 2, only the first 2 will be selected as i.
            '''
            if i > 0 and array[i] == array[i - 1]:
                continue
            left = i + 1
            right = len(array) - 1
            while left < right:
                tmp = array[left] + array[right]
                if tmp + array[i] == target:
                    result.append([array[i], array[left], array[right]])
                    left += 1
                    # ignore all possible duplicate j as well
                    while left < right and array[left] == array[left - 1]:
                        left += 1
                elif tmp + array[i] < target:
                    left += 1
                else:
                    right -= 1
        return result

3. 2 Difference

  • Case 1: sorted
    同向而行
    • Time: O(n)O(n)
    • Space: O(1)O(1)
PYTHON · 仅供阅读
def two_difference_sorted(target, array):
    s = 0
    f = 1
    target = abs(target)
    while s < len(array) and f < len(array):
        if s == f:
            f += 1
            continue
        if array[f] - array[s] < target:
            f += 1
        elif array[f] - array[s] > target:
            s += 1
        else:
            return True
    return False
  • Case 2: unsorted
    • Time: O(n)O(n)
    • Space: O(n)O(n)
PYTHON · 仅供阅读
def two_diff_unsorted(target, array):
    hashset = set()
    for key in array:
        if key - target in hashset or key + target in hashset:  # !!!
            return True
        else:
            hashset.add(key)
    return False

4. Merge elements in k sorted linked lists

  • Case 1: two
    • Time: O(len(one)+len(two))O(len(one)+len(two))
    • Space: O(1)O(1)
PYTHON · 仅供阅读
def merge(one, two):
    if one is None and two is None:
        return None
    fake = ListNode(0)
    cur = fake
    while one is not None and two is not None:
        if one.val < two.val:
            cur.next = one
            one = one.next
        else:
            cur.next = two
            two = two.next
        cur = cur.next
        
    if one is not None:
        cur.next = one
    if two is not None:
        cur.next = two
        
    return fake.next

合并K路比较: 逐个累积合并在等长情况下可达O(nk²)(每路n项);两两归并为O(nk log k);堆做K路合并为O(N log k)、O(k)堆空间,其中N为总项数。下方实现处理的是有序数组,上一段处理链表。

  • Case 2: k
    • Time: O(k+n∗logk)O(k + n * logk), n is number of elements, k is number of array
    • Space: O(k)O(k)
PYTHON · 仅供阅读
class Solution(object):
    def merge(self, arrayOfArrays):
        """
        input: int[][] arrayOfArrays
        return: int[]
        """
        # write your solution here
        import heapq

        if not arrayOfArrays:
            return []

        heap = []
        for i in range(len(arrayOfArrays)):
            if len(arrayOfArrays[i]):
                heap.append((arrayOfArrays[i][0], i, 0))

        heapq.heapify(heap)
        rst = []
        while heap:
            val, index_array, index_element = heapq.heappop(heap)
            rst.append(val)
            if index_element + 1 < len(arrayOfArrays[index_array]):
                heapq.heappush(heap, (arrayOfArrays[index_array][index_element + 1], 
                                      index_array, index_element + 1))

        return rst

整理参考资料