leetcode
leetcode 2301 ~ 2350
老人的数目

老人的数目

难度:

标签:

题目描述

You are given a 0-indexed array of strings details. Each element of details provides information about a given passenger compressed into a string of length 15. The system is such that:

  • The first ten characters consist of the phone number of passengers.
  • The next character denotes the gender of the person.
  • The following two characters are used to indicate the age of the person.
  • The last two characters determine the seat allotted to that person.

Return the number of passengers who are strictly more than 60 years old.

 

Example 1:

Input: details = ["7868190130M7522","5303914400F9211","9273338290F4010"]
Output: 2
Explanation: The passengers at indices 0, 1, and 2 have ages 75, 92, and 40. Thus, there are 2 people who are over 60 years old.

Example 2:

Input: details = ["1313579440F2036","2921522980M5644"]
Output: 0
Explanation: None of the passengers are older than 60.

 

Constraints:

  • 1 <= details.length <= 100
  • details[i].length == 15
  • details[i] consists of digits from '0' to '9'.
  • details[i][10] is either 'M' or 'F' or 'O'.
  • The phone numbers and seat numbers of the passengers are distinct.

代码结果

运行时间: 19 ms, 内存: 15.9 MB


/*
 * 思路:
 * 使用Java Stream API,可以通过map和filter操作来简化代码。
 * 先将字符串流映射为年龄整数流,然后过滤出年龄大于60的元素,最后计算个数。
 */
import java.util.Arrays;

public class Solution {
    public long countSeniors(String[] details) {
        return Arrays.stream(details)
                     .map(detail -> Integer.parseInt(detail.substring(11, 13)))
                     .filter(age -> age > 60)
                     .count();
    }
}

解释

方法:

此题解通过遍历每个乘客的信息字符串,切片获取年龄部分并转换为整数,然后检查是否大于60岁。对于每个年龄大于60岁的乘客,计数器增加1,最后返回计数器的值。

时间复杂度:

O(n)

空间复杂度:

O(1)

代码细节讲解

🦆
在此算法中,如何确保字符串切片`i[11:13]`始终正确地提取年龄信息,是否有对字符串格式的前置验证?
在题解中,并没有明确提到对字符串格式的前置验证。为了确保始终正确地提取年龄信息,算法应该首先验证每个字符串的长度和格式是否符合预期。可以通过正则表达式或字符串长度检查来确保每个字符串都具有正确的格式和长度。如果格式不匹配,应该抛出错误或跳过这些项。
🦆
为什么在将年龄字符串转换为整数时没有考虑到可能存在的非数字字符或格式错误的风险?
题解中直接将年龄字符串转换为整数确实存在一定的风险。理想情况下,应该在转换前添加错误处理逻辑,比如使用try-except结构来捕获并处理ValueError,这种错误会在字符串包含非数字字符时引发。此外,进行转换前,可以先检查字符串是否只包含数字。
🦆
此题解假设每个字符串的长度恒为15,如果存在长度不足或超出的情况,该如何处理?
如果存在长度不足或超出的情况,题解中的方法可能会引发错误,例如索引错误。为了处理这种情况,应在执行切片操作之前验证字符串的长度。如果长度不符合预期,可以选择跳过这个字符串或标记为错误处理,保证程序的健壯性和稳定性。
🦆
算法中直接使用`int(i[11:13]) > 60`进行比较,这种方式是否考虑了年龄字段可能前置有空格的情况?
题解中的方法没有考虑年龄字段前置有空格的情况。如果年龄字段前有空格,直接切片并转换为整数可能会引发ValueError。为了解决这个问题,应在转换为整数之前使用字符串的strip()方法来移除可能存在的前后空格。这样可以确保即使年龄字段有空格,也能正确地进行比较。

相关问题