既不是最小值也不是最大值
难度:
标签:
题目描述
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的情况下,仅排序前三个元素并返回中间值是否总是满足题目的要求?
▷🦆
如果数组中所有元素都是较大或较小的值,例如 [1000, 999, 998],返回中间值是否真的不是最大值或最小值?
▷