LeetCode 题解工作台
最小公共值
给你两个整数数组 nums1 和 nums2 ,它们已经按非降序排序,请你返回两个数组的 最小公共整数 。如果两个数组 nums1 和 nums2 没有公共整数,请你返回 -1 。 如果一个整数在两个数组中都 至少出现一次 ,那么这个整数是数组 nums1 和 nums2 公共 的。 示例 1: 输…
4
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
遍历两个数组,如果两个指针指向的元素相等,则返回该元素;如果两个指针指向的元素不相等,则将指向较小元素的指针右移一位,直到找到相等的元素或者遍历完数组。 时间复杂度 $O(m + n)$,其中 和 分别是两个数组的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你两个整数数组 nums1 和 nums2 ,它们已经按非降序排序,请你返回两个数组的 最小公共整数 。如果两个数组 nums1 和 nums2 没有公共整数,请你返回 -1 。
如果一个整数在两个数组中都 至少出现一次 ,那么这个整数是数组 nums1 和 nums2 公共 的。
示例 1:
输入:nums1 = [1,2,3], nums2 = [2,4] 输出:2 解释:两个数组的最小公共元素是 2 ,所以我们返回 2 。
示例 2:
输入:nums1 = [1,2,3,6], nums2 = [2,3,4,5] 输出:2 解释:两个数组中的公共元素是 2 和 3 ,2 是较小值,所以返回 2 。
提示:
1 <= nums1.length, nums2.length <= 1051 <= nums1[i], nums2[j] <= 109nums1和nums2都是 非降序 的。
解题思路
方法一:双指针
遍历两个数组,如果两个指针指向的元素相等,则返回该元素;如果两个指针指向的元素不相等,则将指向较小元素的指针右移一位,直到找到相等的元素或者遍历完数组。
时间复杂度 ,其中 和 分别是两个数组的长度。空间复杂度 。
class Solution:
def getCommon(self, nums1: List[int], nums2: List[int]) -> int:
i = j = 0
m, n = len(nums1), len(nums2)
while i < m and j < n:
if nums1[i] == nums2[j]:
return nums1[i]
if nums1[i] < nums2[j]:
i += 1
else:
j += 1
return -1
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n log m) when using binary search or O(n + m) for a hash set or two-pointer method. Space complexity is O(1) for two-pointer scan or O(n) if a set is used. |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Do you recognize the sorted array property that allows two-pointer optimization?
- question_mark
Can you identify when a hash set reduces lookup time versus scanning?
- question_mark
How do you handle arrays with duplicates without affecting the minimum common value?
常见陷阱
外企场景- error
Returning the first duplicate match instead of the minimum value.
- error
Using nested loops leading to O(n*m) time instead of O(n + m) or O(n log m).
- error
Neglecting edge cases when one array has no common elements.
进阶变体
外企场景- arrow_right_alt
Find all common values instead of only the minimum.
- arrow_right_alt
Return the maximum common value between two arrays.
- arrow_right_alt
Handle arrays that are not sorted and compare trade-offs in approach.