Leetcode 1822. Sign of the Product of an Array
You are provided with an integer array nums. You need to determine the sign of the product of all values in the array nums.
1.-1.0.nums = [-1,-2,-3,-4,3,2,1]
1nums = [1,5,0,2,-3]
0nums = [-1,1,-1,1,-1]
-1Q: Can the array contain only one element? A: Yes, the array can contain only one element.
Q: Can the input array contain positive, negative, and zero elements? A: Yes, the input can contain any combination of positive, negative, and zero elements.
Q: What is the expected size of the input array? A: The array length can vary, but for the sake of this problem, assume it is within the constraints typically imposed by LeetCode (e.g., up to 1000 elements).
0, return 0 immediately because the product will be 0.-1. If it’s even, the sign will be 1.O(n), where n is the number of elements in the array.public class Solution {
public int arraySign(int[] nums) {
int negativeCount = 0;
for (int num : nums) {
if (num == 0) {
return 0;
}
if (num < 0) {
negativeCount++;
}
}
// If the count of negative numbers is odd, the product is negative
if (negativeCount % 2 == 1) {
return -1;
} else {
return 1;
}
}
}
Initialization: We initialize a counter negativeCount to keep track of the number of negative elements.
num in the array nums, we check if it is 0. If it is, we return 0 because the product will be 0.num is negative, we increment the negativeCount.negativeCount is odd or even.-1, indicating the product is negative.1, indicating the product is positive.This approach ensures that we efficiently determine the sign of the product without actually computing the potentially large product.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?