跳转至

2798. 满足目标工作时长的员工数目

题目描述

公司里共有 n 名员工,按从 0n - 1 编号。每个员工 i 已经在公司工作了 hours[i] 小时。

公司要求每位员工工作 至少 target 小时。

给你一个下标从 0 开始、长度为 n 的非负整数数组 hours 和一个非负整数 target

请你用整数表示并返回工作至少 target 小时的员工数。

 

示例 1:

输入:hours = [0,1,2,3,4], target = 2
输出:3
解释:公司要求每位员工工作至少 2 小时。
- 员工 0 工作 0 小时,不满足要求。
- 员工 1 工作 1 小时,不满足要求。
- 员工 2 工作 2 小时,满足要求。
- 员工 3 工作 3 小时,满足要求。
- 员工 4 工作 4 小时,满足要求。
共有 3 位满足要求的员工。

示例 2:

输入:hours = [5,1,4,2,2], target = 6
输出:0
解释:公司要求每位员工工作至少 6 小时。
共有 0 位满足要求的员工。

 

提示:

  • 1 <= n == hours.length <= 50
  • 0 <= hours[i], target <= 105

解法

方法一:遍历计数

我们可以遍历数组 $hours$,对于每个员工,如果其工作时长 $x$ 大于等于 $target$,则将计数器 $ans$ 加一。

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

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

1
2
3
class Solution:
    def numberOfEmployeesWhoMetTarget(self, hours: List[int], target: int) -> int:
        return sum(x >= target for x in hours)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
    public int numberOfEmployeesWhoMetTarget(int[] hours, int target) {
        int ans = 0;
        for (int x : hours) {
            if (x >= target) {
                ++ans;
            }
        }
        return ans;
    }
}
1
2
3
4
5
6
class Solution {
public:
    int numberOfEmployeesWhoMetTarget(vector<int>& hours, int target) {
        return count_if(hours.begin(), hours.end(), [target](int h) { return h >= target; });
    }
};
1
2
3
4
5
6
7
8
func numberOfEmployeesWhoMetTarget(hours []int, target int) (ans int) {
    for _, x := range hours {
        if x >= target {
            ans++
        }
    }
    return
}
1
2
3
function numberOfEmployeesWhoMetTarget(hours: number[], target: number): number {
    return hours.filter(x => x >= target).length;
}
1
2
3
4
5
6
7
8
impl Solution {
    pub fn number_of_employees_who_met_target(hours: Vec<i32>, target: i32) -> i32 {
        hours
            .iter()
            .filter(|&x| *x >= target)
            .count() as i32
    }
}

评论