leetcode
leetcode 2351 ~ 2400
既不是最小值也不是最大值

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

难度:

标签:

题目描述

Given an integer array nums containing distinct positive integers, find and return any number from the array that is neither the minimum nor the maximum value in the array, or -1 if there is no such number.

Return the selected integer.

 

Example 1:

Input: nums = [3,2,1,4]
Output: 2
Explanation: In this example, the minimum value is 1 and the maximum value is 4. Therefore, either 2 or 3 can be valid answers.

Example 2:

Input: nums = [1,2]
Output: -1
Explanation: Since there is no number in nums that is neither the maximum nor the minimum, we cannot select a number that satisfies the given condition. Therefore, there is no answer.

Example 3:

Input: nums = [2,1,3]
Output: 2
Explanation: Since 2 is neither the maximum nor the minimum value in nums, it is the only valid answer. 

 

Constraints:

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 100
  • All values in nums are distinct

代码结果

运行时间: 36 ms, 内存: 16.6 MB


/*
 * 题目思路:
 * 1. 使用Java Stream API找到最小值和最大值。
 * 2. 过滤出既不是最小值也不是最大值的数字。
 * 3. 返回第一个这样的数字,如果不存在,则返回 -1。
 */

import java.util.Arrays;

public class Solution {
    public int findMiddleElement(int[] nums) {
        if (nums.length <= 2) return -1;

        int min = Arrays.stream(nums).min().getAsInt();
        int max = Arrays.stream(nums).max().getAsInt();

        return Arrays.stream(nums)
                     .filter(num -> num != min && num != max)
                     .findFirst()
                     .orElse(-1);
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        int[] nums1 = {3, 2, 1, 4};
        int[] nums2 = {1, 2};
        int[] nums3 = {2, 1, 3};
        System.out.println(sol.findMiddleElement(nums1)); // 输出: 2
        System.out.println(sol.findMiddleElement(nums2)); // 输出: -1
        System.out.println(sol.findMiddleElement(nums3)); // 输出: 2
    }
}

解释

方法:

题解利用了数组排序的方法来找出既不是最小值也不是最大值的元素。首先,检查数组长度是否大于2,因为只有长度超过2的数组才可能存在既不是最小值也不是最大值的元素。如果数组长度超过2,题解只对数组的前三个元素进行排序,并返回排序后的第二个元素(即中间的元素)。这种方法依赖于题目条件,即数组中的元素都是不同的正整数,因此排序后的第二个元素不会是最小值或最大值。如果数组长度不超过2,直接返回-1,因为这样的数组无法有满足条件的元素。

时间复杂度:

O(1)

空间复杂度:

O(1)

代码细节讲解

🦆
为什么题解中选择只对数组的前三个元素进行排序而不是整个数组?
题解中选择对数组的前三个元素进行排序的原因是基于效率和题目的要求。首先,题目要求找出数组中既不是最小值也不是最大值的任一数字。如果数组中至少有三个不同的元素,那么排序后的第二个元素一定既不是最小值也不是最大值。通过只排序前三个元素,我们可以快速找到这样一个符合条件的元素,同时避免了对整个数组进行排序所需的额外时间复杂度。这种方法在满足题目要求的同时,保证了算法的高效性。
🦆
在数组长度超过3的情况下,仅排序前三个元素并返回中间值是否总是满足题目的要求?
不,仅排序前三个元素并返回中间值并不总是满足题目的要求。虽然在许多情况下这种方法是有效的,但如果整个数组的最小值或最大值位于前三个元素之外,那么仅返回排序后的中间元素可能会导致错误的结果。例如,在数组 [4, 1, 3, 2] 中,如果仅考虑前三个元素 [4, 1, 3],排序后中间值为3,但实际上2也是一个有效答案,且没有被考虑。因此,这种方法虽然在一定程度上降低了计算复杂度,但可能会忽略其他合法的解。
🦆
如果数组中所有元素都是较大或较小的值,例如 [1000, 999, 998],返回中间值是否真的不是最大值或最小值?
在这种特殊情况下,即使数组中的元素值都非常接近(如示例中的1000, 999, 998),排序后的中间值(999)确实既不是数组中的最小值(998)也不是最大值(1000)。因此,即便这些值非常接近,中间值仍然满足题目要求,不是最小值也不是最大值。这证明了即使在元素值非常接近的情况下,本题解法依然有效。

相关问题