-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path20250321.py
More file actions
72 lines (50 loc) · 1.84 KB
/
20250321.py
File metadata and controls
72 lines (50 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
'''
https://leetcode.com/problems/neither-minimum-nor-maximum/description/
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.
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
'''
from typing import List
class Solution:
def findNonMinOrMax(self, nums: List[int]) -> int:
min_num = min(nums)
max_num = max(nums)
for i in range(len(nums)):
if nums[i] != min_num and nums[i] != max_num:
return nums[i]
return -1
solution = Solution()
print(solution.findNonMinOrMax([3,2,1,4])) # -> 2 (or 3)
print(solution.findNonMinOrMax([1,2])) # -> -1
print(solution.findNonMinOrMax([2,1,3])) # -> 2
print(solution.findNonMinOrMax([2,4,25])) # -> 4
'''
Pseudocode:
- Declare min_num as the minumum number found in the nums list
- Declare max_num as the maximum number found in the nums list
- Iterate through the nums list:
- If nums at current index does not equal min_num and nums at current index does not equal max_num
- Return nums at current index
- Return -1 as default value
- Time complexity: O(n)
- Space complexity: O(1)
'''