[LeetCode] Neither Minimum nor Maximum

아르당·2026년 10월 28일

LeetCode

목록 보기
573/602
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

중복 없는 양의 정수를 포함하는 정수 배열 nums가 주어지고, 배열에서 최솟값도 최댓값도 아닌 수를 찾아 반환해라. 만약 그런 수가 없다면 -1을 반환해라.

Example

#1
Input: nums = [3, 2, 1, 4]
Output: 2
Explanation: 최솟값은 1이고 최댓값은 4이다. 2 또는 3이 유효한 답이다.

#2
Input: nums = [1, 2]
Output: -1

#3
Input: nums = [2, 1, 3]
Output: 2

Constraints

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 100
  • nums의 모든 값은 중복이 없다.

Solved

class Solution {
    public int findNonMinOrMax(int[] nums) {
        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;

        for(int i = 0; i < nums.length; i++){
            min = Math.min(min, nums[i]);
            max = Math.max(max, nums[i]);
        }

        for(int i = 0; i < nums.length; i++){
            if(nums[i] != max && nums[i] != min){
                return nums[i];
            }
        }

        return -1;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글