LeetCode 题解工作台
既不是最小值也不是最大值
给你一个整数数组 nums ,数组由 不同正整数 组成,请你找出并返回数组中 任一 既不是 最小值 也不是 最大值 的数字,如果不存在这样的数字,返回 -1 。 返回所选整数。 示例 1: 输入: nums = [3,2,1,4] 输出: 2 解释: 在这个示例中,最小值是 1 ,最大值是 4 。因…
2
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·排序
答案摘要
我们可以先找到数组中的最小值和最大值,分别记为 和 。然后遍历数组,找到第一个不等于 且不等于 的数字,返回即可。 时间复杂度 ,其中 是数组的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·排序 题型思路
题目描述
给你一个整数数组 nums ,数组由 不同正整数 组成,请你找出并返回数组中 任一 既不是 最小值 也不是 最大值 的数字,如果不存在这样的数字,返回 -1 。
返回所选整数。
示例 1:
输入:nums = [3,2,1,4] 输出:2 解释:在这个示例中,最小值是 1 ,最大值是 4 。因此,2 或 3 都是有效答案。
示例 2:
输入:nums = [1,2] 输出:-1 解释:由于不存在既不是最大值也不是最小值的数字,我们无法选出满足题目给定条件的数字。因此,不存在答案,返回 -1 。
示例 3:
输入:nums = [2,1,3] 输出:2 解释:2 既不是最小值,也不是最大值,这个示例只有这一个有效答案。
提示:
1 <= nums.length <= 1001 <= nums[i] <= 100nums中的所有数字互不相同
解题思路
方法一:模拟
我们可以先找到数组中的最小值和最大值,分别记为 和 。然后遍历数组,找到第一个不等于 且不等于 的数字,返回即可。
时间复杂度 ,其中 是数组的长度。空间复杂度 。
class Solution:
def findNonMinOrMax(self, nums: List[int]) -> int:
mi, mx = min(nums), max(nums)
return next((x for x in nums if x != mi and x != mx), -1)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate selects a valid number by sorting and finding an appropriate element.
- question_mark
Candidate quickly identifies that small arrays require an early return of -1.
- question_mark
Candidate avoids overcomplicating the solution by using a sorting-based approach.
常见陷阱
外企场景- error
Returning the wrong element if the array is not sorted.
- error
Forgetting the edge case when the array length is 2, which requires returning -1.
- error
Attempting to solve the problem without sorting the array, leading to incorrect results.
进阶变体
外企场景- arrow_right_alt
Consider using a non-sorting approach for optimization in large arrays.
- arrow_right_alt
Allow the return of the smallest valid number rather than any number.
- arrow_right_alt
Adjust the problem to handle arrays with repeated numbers.