满足目标工作时长的员工数目
难度:
标签:
题目描述
There are n
employees in a company, numbered from 0
to n - 1
. Each employee i
has worked for hours[i]
hours in the company.
The company requires each employee to work for at least target
hours.
You are given a 0-indexed array of non-negative integers hours
of length n
and a non-negative integer target
.
Return the integer denoting the number of employees who worked at least target
hours.
Example 1:
Input: hours = [0,1,2,3,4], target = 2 Output: 3 Explanation: The company wants each employee to work for at least 2 hours. - Employee 0 worked for 0 hours and didn't meet the target. - Employee 1 worked for 1 hours and didn't meet the target. - Employee 2 worked for 2 hours and met the target. - Employee 3 worked for 3 hours and met the target. - Employee 4 worked for 4 hours and met the target. There are 3 employees who met the target.
Example 2:
Input: hours = [5,1,4,2,2], target = 6 Output: 0 Explanation: The company wants each employee to work for at least 6 hours. There are 0 employees who met the target.
Constraints:
1 <= n == hours.length <= 50
0 <= hours[i], target <= 105
代码结果
运行时间: 20 ms, 内存: 16.7 MB
/*
题目思路:
- 使用Java Stream API来处理数组。
- 过滤出工作时间大于等于目标时间的员工,并统计数量。
*/
import java.util.Arrays;
public class Solution {
public long countEmployees(int[] hours, int target) {
// 使用stream过滤出符合条件的员工,并统计数量
return Arrays.stream(hours)
.filter(hour -> hour >= target)
.count();
}
}
解释
方法:
题解采用直接遍历数组的方法,对每个员工的工作时长进行检查。算法通过一个计数器来统计所有满足工作时长大于等于target的员工数量。简单地,每次遇到满足条件的工作时长,计数器就增加1,最后返回这个计数器的值。
时间复杂度:
O(n)
空间复杂度:
O(1)
代码细节讲解
🦆
题解中提到的算法遍历了整个hours数组,这种方法在所有情况下都是最优的吗?或者是否有可能通过其他算法(如排序或二分搜索)进一步优化性能?
▷🦆
在题解实现中,对于每个工作时长的检查是直接比较`i >= target`。请问,在数组hours中如果存在非常大或非常小的值,这种比较操作的性能或结果有何影响?
▷🦆
题解假设了hours数组和target都是非负整数。如果在某些边缘情况下,比如target是负数或hours数组包含负数,该算法是否还能正确运行?
▷🦆
在题解中,如果hours数组长度为0,算法的输出是什么?如何处理这种空数组输入以确保算法的鲁棒性?
▷