1 Star 0 Fork 332

peaking / leetcode

forked from doocs / leetcode 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
README.md 3.99 KB
一键复制 编辑 原始数据 按行查看 历史
ylb 提交于 2024-02-21 08:52 . feat: add problem tags (#2361)

2678. 老人的数目

English Version

题目描述

给你一个下标从 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' 之一。
  • 所有乘客的手机号码和座位号互不相同。

解法

方法一:遍历计数

我们可以遍历 details 中的每个字符串 $x$,并将 $x$ 的第 $12$ 和第 $13$ 个字符(下标为 $11$, $12$)转换为整数,判断是否大于 $60$,如果是则将答案加一。

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

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

class Solution:
    def countSeniors(self, details: List[str]) -> int:
        return sum(int(x[11:13]) > 60 for x in details)
class Solution {
    public int countSeniors(String[] details) {
        int ans = 0;
        for (var x : details) {
            int age = Integer.parseInt(x.substring(11, 13));
            if (age > 60) {
                ++ans;
            }
        }
        return ans;
    }
}
class Solution {
public:
    int countSeniors(vector<string>& details) {
        int ans = 0;
        for (auto& x : details) {
            int age = stoi(x.substr(11, 2));
            ans += age > 60;
        }
        return ans;
    }
};
func countSeniors(details []string) (ans int) {
	for _, x := range details {
		age, _ := strconv.Atoi(x[11:13])
		if age > 60 {
			ans++
		}
	}
	return
}
function countSeniors(details: string[]): number {
    let ans = 0;
    for (const x of details) {
        const age = parseInt(x.slice(11, 13));
        if (age > 60) {
            ++ans;
        }
    }
    return ans;
}
impl Solution {
    pub fn count_seniors(details: Vec<String>) -> i32 {
        let mut ans = 0;

        for s in details.iter() {
            if let Ok(age) = s[11..13].parse::<i32>() {
                if age > 60 {
                    ans += 1;
                }
            }
        }

        ans
    }
}

方法二

function countSeniors(details: string[]): number {
    return details.filter(v => parseInt(v.slice(11, 13)) > 60).length;
}
impl Solution {
    pub fn count_seniors(details: Vec<String>) -> i32 {
        details
            .iter()
            .filter_map(|s| s[11..13].parse::<i32>().ok())
            .filter(|&age| age > 60)
            .count() as i32
    }
}
Java
1
https://gitee.com/peaklee1134/leetcode.git
git@gitee.com:peaklee1134/leetcode.git
peaklee1134
leetcode
leetcode
main

搜索帮助