LeetCode 题解工作台

既不是最小值也不是最大值

给你一个整数数组 nums ,数组由 不同正整数 组成,请你找出并返回数组中 任一 既不是 最小值 也不是 最大值 的数字,如果不存在这样的数字,返回 -1 。 返回所选整数。 示例 1: 输入: nums = [3,2,1,4] 输出: 2 解释: 在这个示例中,最小值是 1 ,最大值是 4 。因…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·排序

bolt

答案摘要

我们可以先找到数组中的最小值和最大值,分别记为 和 。然后遍历数组,找到第一个不等于 且不等于 的数字,返回即可。 时间复杂度 ,其中 是数组的长度。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·排序 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 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 <= 100
  • 1 <= nums[i] <= 100
  • nums 中的所有数字互不相同
lightbulb

解题思路

方法一:模拟

我们可以先找到数组中的最小值和最大值,分别记为 mimimxmx。然后遍历数组,找到第一个不等于 mimi 且不等于 mxmx 的数字,返回即可。

时间复杂度 O(n)O(n),其中 nn 是数组的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
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)
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

既不是最小值也不是最大值题解:数组·排序 | LeetCode #2733 简单