2148. 元素计数
2148. 元素计数
题目
Given an integer array nums, return the number of elements that have both a strictly smaller and a strictly greater element appear in nums.
Example 1:
Input: nums = [11,7,2,15]
Output: 2
Explanation: The element 7 has the element 2 strictly smaller than it and the element 11 strictly greater than it.
Element 11 has element 7 strictly smaller than it and element 15 strictly greater than it.
In total there are 2 elements having both a strictly smaller and a strictly greater element appear in nums.
Example 2:
Input: nums = [-3,3,3,90]
Output: 2
Explanation: The element 3 has the element -3 strictly smaller than it and the element 90 strictly greater than it.
Since there are two elements with the value 3, in total there are 2 elements having both a strictly smaller and a strictly greater element appear in nums.
Constraints:
1 <= nums.length <= 100-10^5 <= nums[i] <= 10^5
题目大意
给你一个整数数组 nums ,统计并返回在 nums 中同时至少具有一个严格较小元素和一个严格较大元素的元素数目。
示例 1:
输入: nums = [11,7,2,15]
输出: 2
解释: 元素 7 :严格较小元素是元素 2 ,严格较大元素是元素 11 。
元素 11 :严格较小元素是元素 7 ,严格较大元素是元素 15 。
总计有 2 个元素都满足在 nums 中同时存在一个严格较小元素和一个严格较大元素。
示例 2:
输入: nums = [-3,3,3,90]
输出: 2
解释: 元素 3 :严格较小元素是元素 -3 ,严格较大元素是元素 90 。
由于有两个元素的值为 3 ,总计有 2 个元素都满足在 nums 中同时存在一个严格较小元素和一个严格较大元素。
提示:
1 <= nums.length <= 100-10^5 <= nums[i] <= 10^5
解题思路
- 初始化最小值和最大值:
- 使用
min和max分别记录数组的最小值和最大值。 - 使用
minCount和maxCount分别记录数组中值等于最小值和最大值的元素个数。 - 初始化为正无穷和负无穷,以便在遍历过程中正确更新。
- 使用
- 遍历数组:
- 更新
min和max:- 如果当前元素小于
min,更新min并将最小值的计数minCount重置为 1。 - 如果当前元素等于
min,仅增加minCount。 - 同样处理最大值
max和最大值计数maxCount。
- 如果当前元素小于
- 更新
- 计算结果:
- 如果最小值和最大值相等(数组中的所有元素都相同),返回
0,因为不存在符合条件的元素。 - 否则,返回数组长度减去最小值和最大值的计数之和,即
nums.length - minCount - maxCount。
- 如果最小值和最大值相等(数组中的所有元素都相同),返回
复杂度分析
- 时间复杂度:
O(n),其中n是数组的长度,只需遍历数组一次。 - 空间复杂度:
O(1),仅使用常量空间。
代码
/**
* @param {number[]} nums
* @return {number}
*/
var countElements = function (nums) {
let min = Infinity,
minCount = 0;
let max = -Infinity,
maxCount = 0;
for (let num of nums) {
if (num < min) {
min = num;
minCount = 1; // 重置计数
} else if (num === min) {
minCount++; // 增加计数
}
if (num > max) {
max = num;
maxCount = 1; // 重置计数
} else if (num === max) {
maxCount++; // 增加计数
}
}
if (min === max) return 0; // 所有元素相同
return nums.length - minCount - maxCount;
};
相关题目
| 题号 | 标题 | 题解 | 标签 | 难度 | 力扣 |
|---|---|---|---|---|---|
| 744 | 寻找比目标字母大的最小字母 | [✓] | 数组 二分查找 | 🟢 | 🀄️ 🔗 |
