[Solution] 2148. Count Elements With Strictly Smaller and Greater Elements

·

1 min read

Problem

Problem_Link

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

  1. loop to find max and min: do not count separately. you can find max and min in O(n) NOT O(2n)
  2. 2nd loop count a strictly smaller and a strictly greater elements: do not count duplicated min and max.
  3. return count