Skip to content

Commit 52bbfcc

Browse files
committed
feat: solve No.1822
1 parent 6dc9e61 commit 52bbfcc

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# 1822. Sign of the Product of an Array
2+
3+
- Difficulty: Easy.
4+
- Related Topics: Array, Math.
5+
- Similar Questions: .
6+
7+
## Problem
8+
9+
There is a function `signFunc(x)` that returns:
10+
11+
12+
13+
- `1` if `x` is positive.
14+
15+
- `-1` if `x` is negative.
16+
17+
- `0` if `x` is equal to `0`.
18+
19+
20+
You are given an integer array `nums`. Let `product` be the product of all values in the array `nums`.
21+
22+
Return `signFunc(product)`.
23+
24+
 
25+
Example 1:
26+
27+
```
28+
Input: nums = [-1,-2,-3,-4,3,2,1]
29+
Output: 1
30+
Explanation: The product of all values in the array is 144, and signFunc(144) = 1
31+
```
32+
33+
Example 2:
34+
35+
```
36+
Input: nums = [1,5,0,2,-3]
37+
Output: 0
38+
Explanation: The product of all values in the array is 0, and signFunc(0) = 0
39+
```
40+
41+
Example 3:
42+
43+
```
44+
Input: nums = [-1,1,-1,1,-1]
45+
Output: -1
46+
Explanation: The product of all values in the array is -1, and signFunc(-1) = -1
47+
```
48+
49+
 
50+
**Constraints:**
51+
52+
53+
54+
- `1 <= nums.length <= 1000`
55+
56+
- `-100 <= nums[i] <= 100`
57+
58+
59+
60+
## Solution
61+
62+
```javascript
63+
/**
64+
* @param {number[]} nums
65+
* @return {number}
66+
*/
67+
var arraySign = function(nums) {
68+
var res = 1;
69+
for (var i = 0; i < nums.length; i++) {
70+
res *= nums[i] > 0 ? 1 : (nums[i] === 0 ? 0 : -1);
71+
}
72+
return res;
73+
};
74+
```
75+
76+
**Explain:**
77+
78+
nope.
79+
80+
**Complexity:**
81+
82+
* Time complexity : O(n).
83+
* Space complexity : O(n).

0 commit comments

Comments
 (0)