710065. Unoccupied Computers
Easy
Unoccupied Computers
Summary
The problem is about finding all unoccupied computers in a given list. The key concept involved is working with arrays and iterating through them to find specific conditions.
Detailed Explanation
We are given an array computers where each element represents the state of a computer (0 for occupied, 1 for unoccupied). Our goal is to find all the unoccupied computers in this array.
To solve this problem, we will iterate through the array and check each computer's state. If the state is 1 (unoccupied), we add it to our result list.
Here is a step-by-step breakdown of the solution:
- Initialize an empty list
resultto store the unoccupied computers. - Iterate through the
computersarray using a for loop or any other suitable iteration method. - For each computer, check its state by accessing the corresponding element in the
computersarray. - If the state is 1 (unoccupied), add the index of this computer to the
resultlist. - After iterating through all computers, return the
resultlist.
Time complexity: O(n), where n is the number of computers. Space complexity: O(1) as we only use a constant amount of space to store the result.
Optimized Solutions
Java
public int[] findUnoccupiedComputers(int[] computers) {
List<Integer> result = new ArrayList<>();
for (int i = 0; i < computers.length; i++) {
if (computers[i] == 1) {
result.add(i);
}
}
return result.stream().mapToInt(Integer::intValue).toArray();
}