Problem Description
Explanation:
To solve this problem, we need to calculate the product of all elements in the given array nums
. Then, we can determine the sign of the product based on the rules provided in the problem description.
- Initialize a variable
product
to store the product of all elements in the array. - Iterate through each element in the array and update the product.
- Determine the sign of the product using the
signFunc
function. - Return the sign of the product.
Time Complexity:
The time complexity of this solution is O(N), where N is the number of elements in the input array nums
.
Space Complexity:
The space complexity of this solution is O(1) as we are using a constant amount of extra space.
Solutions
class Solution {
public int arraySign(int[] nums) {
int product = 1;
for (int num : nums) {
product *= num;
}
return signFunc(product);
}
private int signFunc(int x) {
if (x > 0) {
return 1;
} else if (x < 0) {
return -1;
} else {
return 0;
}
}
}
Loading editor...