[LeetCode]#1822. Sign of the Product of an Array
Jan 20, 2022
Environment: Python 3.8
Key technique: for, if
There is a function signFunc(x)
that returns:
1
ifx
is positive.-1
ifx
is negative.0
ifx
is equal to0
.
You are given an integer array nums
. Let product
be the product of all values in the array nums
.
Return signFunc(product)
.
Example 1:
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
Analysis:
- init ans=1
- ans=ans x nums[i] by using loop
- if ans >0, return 1
- if ans <0, return -1
- if ans==0, return 0
Solution:
class Solution:
def arraySign(self, nums):
ans=1
for i in range(len(nums)):
ans=ans*nums[i]
if ans >0:
return 1
if ans <0:
return -1
if ans ==0:
return 0
Submissions: