99클럽 코테 스터디 32일차 TIL (비기너)

jeenie's avatar
Jun 19, 2024
99클럽 코테 스터디 32일차 TIL (비기너)

<문제>

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

<문제해설>

체감 난이도: 매우 easy

서로 다른 양의 정수를 가진 배열 nums가 있다. 이 때 배열에서 가장 작은 수(minimum)와 가장 큰 수(maximum)를 제외한 ‘임의의 숫자’를 반환하라.

<풀이>

class Solution {
    public int findNonMinOrMax(int[] nums) {
        //길이가 1,2인 경우에는 바로 반환
        if(nums.length <= 2){
            return -1;
        }

        Arrays.sort(nums);

        return nums[1];
    }
}

<접근방식>

  1. 길이가 2 이하일 때는 바로 -1을 반환하였다.

  2. Arrays.sort 를 통해 nums를 오름차순 정렬한 뒤, 2번째 원소를 반환하였다. (1번째, 마지막 원소를 제외하고 확실하게 존재하는 원소)

<마무리하며>

Arrays.sort()를 떠올리지 못했다면 for문을 통해서 중간값을 찾는 어려운 방법으로 갔을 것 같다..!

Share article
RSSPowered by inblog