题目描述
这是 LeetCode 上的 1822. 数组元素积的符号 ,难度为 简单。
Tag : 「模拟」
已知函数
signFunc(x)
将会根据
x
的正负返回特定值:
- 如果
是正数,返回 x
。1
- 如果
是负数,返回 x
。-1
- 如果
是等于 x
,返回 0
。0
给你一个整数数组
nums
。令
product
为数组
nums
中所有元素值的乘积。
返回
signFunc(product)
。
示例 1:
输入:nums = [-1,-2,-3,-4,3,2,1]
输出:1
解释:数组中所有值的乘积是 144 ,且 signFunc(144) = 1
示例 2:
输入:nums = [1,5,0,2,-3]
输出:0
解释:数组中所有值的乘积是 0 ,且 signFunc(0) = 0
示例 3:
输入:nums = [-1,1,-1,1,-1]
输出:-1
解释:数组中所有值的乘积是 -1 ,且 signFunc(-1) = -1
提示:
模拟
根据题意进行模拟。
Java 代码:
class Solution {
public int arraySign(int[] nums) {
int ans = 1;
for (int x : nums) {
if (x == 0) return 0;
if (x < 0) ans *= -1;
}
return ans;
}
}
TypeScript 代码:
function arraySign(nums: number[]): number {
let ans = 0
for (const x of nums) {
if (x == 0) return 0
if (x < 0) ans *= -1
}
return ans
}
Python 代码:
class Solution:
def arraySign(self, nums: List[int]) -> int:
ans = 1
for x in nums:
if x == 0:
return 0
if x < 0:
ans *= -1
return ans
- 时间复杂度:
- 空间复杂度:
最后
这是我们「刷穿 LeetCode」系列文章的第
No.1822s
篇,系列开始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道题目,部分是有锁题,我们将先把所有不带锁的题目刷完。
在这个系列文章里面,除了讲解解题思路以外,还会尽可能给出最为简洁的代码。如果涉及通解还会相应的代码模板。