老人的数目
难度:
标签:
题目描述
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]`始终正确地提取年龄信息,是否有对字符串格式的前置验证?
▷🦆
为什么在将年龄字符串转换为整数时没有考虑到可能存在的非数字字符或格式错误的风险?
▷🦆
此题解假设每个字符串的长度恒为15,如果存在长度不足或超出的情况,该如何处理?
▷🦆
算法中直接使用`int(i[11:13]) > 60`进行比较,这种方式是否考虑了年龄字段可能前置有空格的情况?
▷