Problem#
Implement a function signFunc(x)
that returns:
1
if x
is positive.
-1
if x
is negative.
0
if x
is equal to 0
.
You are given an integer array nums
. Let product
be the product of all values in the array nums
.
Return signFunc(product)
.
Examples#
Example 1#
1
2
3
|
Input: nums = [-1,-2,-3,-4,3,2,1]
Output: 1
Explanation: The product of all values in the array is 144, and signFunc(144) = 1
|
Example 2#
1
2
3
|
Input: nums = [1,5,0,2,-3]
Output: 0
Explanation: The product of all values in the array is 0, and signFunc(0) = 0
|
Example 3#
1
2
3
|
Input: nums = [-1,1,-1,1,-1]
Output: -1
Explanation: The product of all values in the array is -1, and signFunc(-1) = -1
|
Constraints#
1 <= nums.length <= 1000
-100 <= nums[i] <= 100
Solution#
Method 1 – Count Negatives and Zeros#
Intuition#
The sign of the product is 0 if any element is 0, otherwise it is -1 if there are an odd number of negatives, else 1.
Approach#
- Initialize a variable to count negatives.
- If any element is 0, return 0.
- If the count of negatives is odd, return -1; else return 1.
Code#
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#include <vector>
using namespace std;
class Solution {
public:
int arraySign(vector<int>& nums) {
int neg = 0;
for (int x : nums) {
if (x == 0) return 0;
if (x < 0) ++neg;
}
return neg % 2 ? -1 : 1;
}
};
|
1
2
3
4
5
6
7
8
9
10
|
class Solution {
public int arraySign(int[] nums) {
int neg = 0;
for (int x : nums) {
if (x == 0) return 0;
if (x < 0) ++neg;
}
return neg % 2 == 1 ? -1 : 1;
}
}
|
1
2
3
4
5
6
7
8
9
|
class Solution:
def arraySign(self, nums):
neg = 0
for x in nums:
if x == 0:
return 0
if x < 0:
neg += 1
return -1 if neg % 2 else 1
|
Complexity#
- ⏰ Time complexity:
O(n)
— Single pass through the array.
- 🧺 Space complexity:
O(1)
— No extra space used.