This problem cannot use two pointers because it is not linear. The core of using a heap is to first put all {nums1[0], nums2[j]} into the heap (0 <= j <= nums2.size()), then remove the pair {i, j} with the smallest sum from the heap. When j is fixed, among the larger values, {i+1, j} is the smallest.
Why can j remain unchanged? Because the advancement of j (i.e., j+1) has already been added to the heap during initialization ({nums1[0], nums2[j]}).
Example 1’snums1 = [1, 7, 11],nums2 = [2, 4, 6]. We calculate the sum of each pair and obtain a matrix M, where Mi,j=nums1[i]+nums2[j].
M=39135111571317
Sincenums2is increasing, so each row of the matrix is increasing. The problem is equivalent to: merge n sorted lists and find the first k smallest elements. (Where n isnums1(length) According to the heap approach of merging K sorted linked lists from P23:
Add the first number Mi,0 of each row of the matrix and its position (i,0) to the min-heap.
Loop k times.
Each loop, pop the top of the heap, take the top M∗i,j corresponding number pair into the answer, take the element to the right of the heap top M∗i,j+1 and its position (i,j+1) into the heap.