g2701_2800.s2733_neither_minimum_nor_maximum.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g2701_2800.s2733_neither_minimum_nor_maximum;
// #Easy #Array #Sorting #2023_09_22_Time_4_ms_(99.76%)_Space_43.9_MB_(27.58%)
/**
* 2733 - Neither Minimum nor Maximum\.
*
* Easy
*
* 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
**/
public class Solution {
public int findNonMinOrMax(int[] nums) {
int mn = 999;
int mx = -1;
for (int num : nums) {
mn = Math.min(num, mn);
mx = Math.max(num, mx);
}
for (int num : nums) {
if (num != mn && num != mx) {
return num;
}
}
return -1;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy