返回介绍

solution / 2700-2799 / 2733.Neither Minimum nor Maximum / README_EN

发布于 2024-06-17 01:03:00 字数 3795 浏览 0 评论 0 收藏 0

2733. Neither Minimum nor Maximum

中文文档

Description

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

Solutions

Solution 1

class Solution:
  def findNonMinOrMax(self, nums: List[int]) -> int:
    return -1 if len(nums) < 3 else sorted(nums)[1]
class Solution {
  public int findNonMinOrMax(int[] nums) {
    int mi = 100, mx = 0;
    for (int x : nums) {
      mi = Math.min(mi, x);
      mx = Math.max(mx, x);
    }
    for (int x : nums) {
      if (x != mi && x != mx) {
        return x;
      }
    }
    return -1;
  }
}
class Solution {
public:
  int findNonMinOrMax(vector<int>& nums) {
    int mi = *min_element(nums.begin(), nums.end());
    int mx = *max_element(nums.begin(), nums.end());
    for (int x : nums) {
      if (x != mi && x != mx) {
        return x;
      }
    }
    return -1;
  }
};
func findNonMinOrMax(nums []int) int {
  mi, mx := slices.Min(nums), slices.Max(nums)
  for _, x := range nums {
    if x != mi && x != mx {
      return x
    }
  }
  return -1
}
impl Solution {
  pub fn find_non_min_or_max(nums: Vec<i32>) -> i32 {
    let mut mi = 100;
    let mut mx = 0;

    for &ele in nums.iter() {
      if ele < mi {
        mi = ele;
      }
      if ele > mx {
        mx = ele;
      }
    }

    for &ele in nums.iter() {
      if ele != mi && ele != mx {
        return ele;
      }
    }

    -1
  }
}

Solution 2

class Solution:
  def findNonMinOrMax(self, nums: List[int]) -> int:
    mi, mx = min(nums), max(nums)
    for x in nums:
      if x != mi and x != mx:
        return x
    return -1

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文