LeetCode 题解工作台
找出与数组相加的整数 I
给你两个长度相等的数组 nums1 和 nums2 。 数组 nums1 中的每个元素都与变量 x 所表示的整数相加。如果 x 为负数,则表现为元素值的减少。 在与 x 相加后, nums1 和 nums2 相等 。当两个数组中包含相同的整数,并且这些整数出现的频次相同时,两个数组 相等 。 返回整…
1
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·driven
答案摘要
我们可以分别求出两个数组的最小值,然后返回两个最小值的差值即可。 时间复杂度 ,其中 为数组的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路
题目描述
给你两个长度相等的数组 nums1 和 nums2。
数组 nums1 中的每个元素都与变量 x 所表示的整数相加。如果 x 为负数,则表现为元素值的减少。
在与 x 相加后,nums1 和 nums2 相等 。当两个数组中包含相同的整数,并且这些整数出现的频次相同时,两个数组 相等 。
返回整数 x 。
示例 1:
输入:nums1 = [2,6,4], nums2 = [9,7,5]
输出:3
解释:
与 3 相加后,nums1 和 nums2 相等。
示例 2:
输入:nums1 = [10], nums2 = [5]
输出:-5
解释:
与 -5 相加后,nums1 和 nums2 相等。
示例 3:
输入:nums1 = [1,1,1,1], nums2 = [1,1,1,1]
输出:0
解释:
与 0 相加后,nums1 和 nums2 相等。
提示:
1 <= nums1.length == nums2.length <= 1000 <= nums1[i], nums2[i] <= 1000- 测试用例以这样的方式生成:存在一个整数
x,使得nums1中的每个元素都与x相加后,nums1与nums2相等。
解题思路
方法一:求最小值差
我们可以分别求出两个数组的最小值,然后返回两个最小值的差值即可。
时间复杂度 ,其中 为数组的长度。空间复杂度 。
class Solution:
def addedInteger(self, nums1: List[int], nums2: List[int]) -> int:
return min(nums2) - min(nums1)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate demonstrates proficiency with sorting techniques in array-based problems.
- question_mark
The candidate is able to efficiently identify and leverage the one-to-one correspondence between sorted arrays.
- question_mark
The candidate handles edge cases, such as arrays being identical, with clarity and correctness.
常见陷阱
外企场景- error
Failing to account for edge cases, such as when nums1 and nums2 are already identical.
- error
Overcomplicating the solution with unnecessary steps instead of using sorting for direct comparison.
- error
Incorrectly assuming a transformation is not possible when nums1 is already equal to nums2.
进阶变体
外企场景- arrow_right_alt
What happens if the arrays are very large and sorting takes longer than expected?
- arrow_right_alt
How would this solution change if the transformation was a more complex operation, not just addition?
- arrow_right_alt
Can this solution be adapted for arrays with non-integer elements?