leetcode
leetcode 2351 ~ 2400
满足目标工作时长的员工数目

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

难度:

标签:

题目描述

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数组,这种方法在所有情况下都是最优的吗?或者是否有可能通过其他算法(如排序或二分搜索)进一步优化性能?
遍历整个hours数组是最直接的方法,时间复杂度为O(n),其中n是数组hours的长度。这种方法在所有情况下都是最优的,因为它保证了只遍历一次数组,且不需要额外的数据结构。使用排序或二分搜索等方法通常需要先对数组进行排序,其时间复杂度至少为O(n log n),这在本题中不是性能上的优化。因此,对于这个问题,直接遍历是最高效的解决方式。
🦆
在题解实现中,对于每个工作时长的检查是直接比较`i >= target`。请问,在数组hours中如果存在非常大或非常小的值,这种比较操作的性能或结果有何影响?
在Python中,比较操作(如`i >= target`)是非常高效的,并且可以准确处理非常大或非常小的整数值。Python的整数是动态大小的,可以处理比标准整数类型更大或更小的值。因此,无论hours数组中的值有多大或多小,比较操作都可以正确执行,不会对性能或结果产生负面影响。
🦆
题解假设了hours数组和target都是非负整数。如果在某些边缘情况下,比如target是负数或hours数组包含负数,该算法是否还能正确运行?
该算法在逻辑上可以处理包含负数的hours数组或负数的target。比较操作`i >= target`在数学上仍然有效,无论i或target的值是正是负。例如,如果target为负数,任何非负的工作时长都将满足条件,如果hours中的元素也为负数,只有当它们大于等于target时才会被计数。因此,算法在逻辑上无需修改即可处理这种情况。
🦆
在题解中,如果hours数组长度为0,算法的输出是什么?如何处理这种空数组输入以确保算法的鲁棒性?
如果hours数组长度为0,算法会正确地返回0,因为没有员工的工作时长可以检查。这种情况下算法已经具备了处理空数组的能力,因为计数器的初始值为0,并且在没有遍历任何元素的情况下直接返回。这保证了算法对于空数组输入的鲁棒性。

相关问题