{ "cells": [ { "cell_type": "markdown", "source": [ "You are given two integer arrays **nums1** and **nums2** sorted in ascending\n", "order and an integer **k**.\n", "\n", "Define a pair **(u,v)** which consists of one element from the first array and\n", "one element from the second array.\n", "\n", "Find the k pairs **(u 1,v1),(u2,v2) ...(uk,vk)** with the smallest sums.\n", "\n", "**Example 1:**\n", "\n", "\n", "\n", " Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3\n", " Output: [[1,2],[1,4],[1,6]]\n", " Explanation: The first 3 pairs are returned from the sequence:\n", " [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]\n", "\n", "**Example 2:**\n", "\n", "\n", "\n", " Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2\n", " Output: [1,1],[1,1]\n", " Explanation: The first 2 pairs are returned from the sequence:\n", " [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]\n", "\n", "**Example 3:**\n", "\n", "\n", "\n", " Input: nums1 = [1,2], nums2 = [3], k = 3\n", " Output: [1,3],[2,3]\n", " Explanation: All possible pairs are returned from the sequence: [1,3],[2,3]" ], "metadata": {} }, { "outputs": [ { "output_type": "execute_result", "data": { "text/plain": "k_smallest_pairs (generic function with 1 method)" }, "metadata": {}, "execution_count": 1 } ], "cell_type": "code", "source": [ "# @lc code=start\n", "using LeetCode\n", "using DataStructures\n", "function k_smallest_pairs(nums1::Vector{Int}, nums2::Vector{Int}, k::Int)\n", " hp = Tuple{Int, Int}[]\n", " odr = Base.Order.By(x -> -x[1] - x[2])\n", " for n1 in nums1, n2 in nums2\n", " heappush!(hp, (n1, n2), odr)\n", " length(hp) > k && heappop!(hp, odr)\n", " end\n", " sort!(hp; by = x -> x[1] + x[2])\n", "end\n", "# @lc code=end" ], "metadata": {}, "execution_count": 1 }, { "cell_type": "markdown", "source": [ "---\n", "\n", "*This notebook was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*" ], "metadata": {} } ], "nbformat_minor": 3, "metadata": { "language_info": { "file_extension": ".jl", "mimetype": "application/julia", "name": "julia", "version": "1.10.1" }, "kernelspec": { "name": "julia-1.10", "display_name": "Julia 1.10.1", "language": "julia" } }, "nbformat": 4 }