Java实现 LeetCode 373 查找和最小的K对数字

373. 查找和最小的K对数字

给定两个以升序排列的整形数组 nums1 和 nums2, 以及一个整数 k。

定义一对值 (u,v),其中第一个元素来自 nums1,第二个元素来自 nums2。

找到和最小的 k 对数字 (u1,v1), (u2,v2) … (uk,vk)。

示例 1:

输入: nums1 = [1,7,11], nums2 = [2,4,6], k = 3
输出: [1,2],[1,4],[1,6]
解释: 返回序列中的前 3 对数:

 [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]

示例 2:

输入: nums1 = [1,1,2], nums2 = [1,2,3], k = 2
输出: [1,1],[1,1]
解释: 返回序列中的前 2 对数:
     [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]

示例 3:

输入: nums1 = [1,2], nums2 = [3], k = 3 
输出: [1,3],[2,3]
解释: 也可能序列中所有的数对都被返回:[1,3],[2,3]

PS:
indexArray的标记每一次都会加加,以至于是不能找到重复的,

class Solution {
     public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
        List<List<Integer>> result = new ArrayList<>();
        if (k <= 0) {
            return result;
        }
        // 搜索的起始位置,主要起到优化作用减少循环次数
        int[] indexArray = new int[nums1.length];
        int startIndex = 0;
        while (result.size() < k) {

            // 记录当前最小对的和
            int min = Integer.MAX_VALUE;

            // 记录当前最小对的位置
            int currentIndex = -1;
            for (int i = startIndex; i < nums1.length; i++) {
                // 这里说明nums1[i]已经与nums2中所有元素结对入队列,之后的搜索从nums1[i + 1]开始
                if (indexArray[i] == nums2.length) {
                    startIndex = i + 1;
                    continue;
                }

                // 比较,选择最小的
                if (nums1[i] + nums2[indexArray[i]] < min) {
                    min = nums1[i] + nums2[indexArray[i]];
                    currentIndex = i;
                }

                // nums1和nums2都升序,所以nums1[i] + nums2[a] <= nums1[nums1.length - 1] + nums2[a]
                if (indexArray[i] == indexArray[indexArray.length - 1]) {
                    break;
                }
            }

            // 防止k > nums1.length * nums2.length,出现则直接跳出
            if (currentIndex == -1) {
                break;
            }

            // 最小的对入队
            List<Integer> data = new ArrayList<>();
            result.add(data);
            data.add(nums1[currentIndex]);
            data.add(nums2[indexArray[currentIndex]]);
            indexArray[currentIndex] = indexArray[currentIndex] + 1;
        }

        return result;
    }
}
发布了1487 篇原创文章 · 获赞 2万+ · 访问量 185万+

猜你喜欢

转载自blog.csdn.net/a1439775520/article/details/104797396