728x90
반응형
✨ 문제
Neither Minimum nor Maximum
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.
https://leetcode.com/problems/neither-minimum-nor-maximum/description/
✨ 최종코드
class Solution {
public int findNonMinOrMax(int[] nums) {
if (nums.length <= 2)
return -1;
int max = nums[0];
int min = nums[0];
max = Math.max(max, Math.max(nums[1], nums[2]));
min = Math.min(min, Math.min(nums[1], nums[2]));
return nums[0] + nums[1] + nums[2] - max - min;
}
}
처음에는 배열을 정렬한 뒤 nums의 첫번째 값을 반환하도록 하였는데 효율이 너무 떨어져 다시 작성했다.
nums의 길이가 2 이하인 경우 최소값, 최대값 이외의 값이 없으므로 -1을 반환하도록 하였다.
변수 max와 min을 선언하여 최대값과 최소값을 저장한다. 그리고 nums의 3번째값까지 더한 뒤 max와 min을 빼주어 최대값과 최소값 이외의 값을 반환해주었다.
728x90
반응형