LeetCode 题解工作台

元素计数

给你一个整数数组 nums ,统计并返回在 nums 中同时至少具有一个严格较小元素和一个严格较大元素的元素数目。 示例 1: 输入: nums = [11,7,2,15] 输出: 2 解释: 元素 7 :严格较小元素是元素 2 ,严格较大元素是元素 11 。 元素 11 :严格较小元素是元素 7 …

category

3

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·排序

bolt

答案摘要

根据题目描述,我们可以先求出数组 的最小值 和最大值 ,然后遍历数组 ,统计满足 $\textit{mi} < x < \textit{mx}$ 的元素个数即可。 时间复杂度 ,其中 是数组 的长度。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·排序 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 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
  • -105 <= nums[i] <= 105
lightbulb

解题思路

方法一:求最小值和最大值

根据题目描述,我们可以先求出数组 nums\textit{nums} 的最小值 mi\textit{mi} 和最大值 mx\textit{mx},然后遍历数组 nums\textit{nums},统计满足 mi<x<mx\textit{mi} < x < \textit{mx} 的元素个数即可。

时间复杂度 O(n)O(n),其中 nn 是数组 nums\textit{nums} 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
class Solution:
    def countElements(self, nums: List[int]) -> int:
        mi, mx = min(nums), max(nums)
        return sum(mi < x < mx for x in nums)
speed

复杂度分析

指标
时间complexity is O(n log n) due to sorting, then O(n) for counting, giving overall O(n log n). Space complexity is O(1) extra if in-place sorting is used, or O(n) if a copy is made.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    The array length is small enough to consider sorting first.

  • question_mark

    They may hint at excluding only minimum and maximum elements.

  • question_mark

    Expect to discuss edge cases with duplicates of min or max.

warning

常见陷阱

外企场景
  • error

    Counting minimum or maximum elements incorrectly.

  • error

    Not handling duplicate values properly, especially when min or max repeats.

  • error

    Using nested loops unnecessarily, increasing time complexity.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Count elements with at least k strictly smaller and greater elements.

  • arrow_right_alt

    Return indices instead of counts for elements with both smaller and greater values.

  • arrow_right_alt

    Apply the same pattern to a 2D matrix by flattening and counting elements.

help

常见问题

外企场景

元素计数题解:数组·排序 | LeetCode #2148 简单