Photo by Glenn Carstens-Peters on Unsplash
[Solution] 2148. Count Elements With Strictly Smaller and Greater Elements
Problem
Solutions (time, space)
O(n), O(1)
class Solution {
public int countElements(int[] nums) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
int count = 0;
for (int temp : nums) {
max = Math.max(max, temp);
min = Math.min(min, temp);
}
for (int temp : nums) {
if (temp > min && temp < max) {
count++;
}
}
return count;
}
}
Explanation
- loop to find max and min: do not count separately. you can find max and min in O(n) NOT O(2n)
- 2nd loop count a strictly smaller and a strictly greater elements: do not count duplicated min and max.
- return count