leetcode 1822. 数组元素积的符号

解题思路

数组中存在0,结果为0。否则,奇数个负数,结果为-1;偶数个负数结果为1

时间复杂度

O(n)

空间复杂度

O(1)

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
def arraySign(self, nums: List[int]) -> int:
sign = 1
is_zero = False

for num in nums:
if num == 0:
is_zero = True
break
if num < 0:
sign *= -1

return not is_zero and sign or 0