LeetCode 题解工作台

老人的数目

给你一个下标从 0 开始的字符串数组 details 。 details 中每个元素都是一位乘客的信息,信息用长度为 15 的字符串表示,表示方式如下: 前十个字符是乘客的手机号码。 接下来的一个字符是乘客的性别。 接下来两个字符是乘客的年龄。 最后两个字符是乘客的座位号。 请你返回乘客中年龄 严格…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·string

bolt

答案摘要

我们可以遍历 `details` 中的每个字符串 ,并将 的第 和第 个字符(下标为 , )转换为整数,判断是否大于 ,如果是则将答案加一。 遍历结束后,返回答案即可。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 0 开始的字符串数组 details 。details 中每个元素都是一位乘客的信息,信息用长度为 15 的字符串表示,表示方式如下:

  • 前十个字符是乘客的手机号码。
  • 接下来的一个字符是乘客的性别。
  • 接下来两个字符是乘客的年龄。
  • 最后两个字符是乘客的座位号。

请你返回乘客中年龄 严格大于 60 岁 的人数。

 

示例 1:

输入:details = ["7868190130M7522","5303914400F9211","9273338290F4010"]
输出:2
解释:下标为 0 ,1 和 2 的乘客年龄分别为 75 ,92 和 40 。所以有 2 人年龄大于 60 岁。

示例 2:

输入:details = ["1313579440F2036","2921522980M5644"]
输出:0
解释:没有乘客的年龄大于 60 岁。

 

提示:

  • 1 <= details.length <= 100
  • details[i].length == 15
  • details[i] 中的数字只包含 '0' 到 '9' 。
  • details[i][10] 是 'M' ,'F' 或者 'O' 之一。
  • 所有乘客的手机号码和座位号互不相同。
lightbulb

解题思路

方法一:遍历计数

我们可以遍历 details 中的每个字符串 xx,并将 xx 的第 1212 和第 1313 个字符(下标为 1111, 1212)转换为整数,判断是否大于 6060,如果是则将答案加一。

遍历结束后,返回答案即可。

时间复杂度 O(n)O(n),其中 nndetails 的长度。空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def countSeniors(self, details: List[str]) -> int:
        return sum(int(x[11:13]) > 60 for x in details)
speed

复杂度分析

指标
时间O(n)
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate should focus on efficiently parsing and comparing the age values.

  • question_mark

    A clear understanding of string indexing and conversion to integers is essential for solving this problem.

  • question_mark

    The candidate must handle edge cases, such as when no passengers are older than 60.

warning

常见陷阱

外企场景
  • error

    Incorrectly handling the substring extraction for the age (indexing issues).

  • error

    Forgetting to convert the age from a string to an integer before comparison.

  • error

    Overcomplicating the solution by introducing unnecessary steps or data structures.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Modify the problem to count passengers over a different age threshold (e.g., 50 or 70).

  • arrow_right_alt

    Handle cases where the passenger details contain invalid or corrupted data (e.g., malformed strings).

  • arrow_right_alt

    Implement a more complex filtering system based on other passenger details, such as gender or seat number.

help

常见问题

外企场景

老人的数目题解:数组·string | LeetCode #2678 简单