LC 1822.Sign of the Product of an Array

题目描述

这是 LeetCode 上的 1822. 数组元素积的符号 ,难度为简单

已知函数 signFunc(x) 将会根据 x 的正负返回特定值:

  • 如果 x 是正数,返回 1
  • 如果 x 是负数,返回 -1
  • 如果 x 是等于 0 ,返回 0

给你一个整数数组 nums 。令 product 为数组 nums 中所有元素值的乘积。

返回 signFunc(product)

示例 1:

1
2
3
输入:nums = [-1,-2,-3,-4,3,2,1]
输出:1
解释:数组中所有值的乘积是 144 ,且 signFunc(144) = 1

示例 2:

1
2
3
输入:nums = [1,5,0,2,-3]
输出:0
解释:数组中所有值的乘积是 0 ,且 signFunc(0) = 0

示例 3:

1
2
3
输入:nums = [-1,1,-1,1,-1]
输出:-1
解释:数组中所有值的乘积是 -1 ,且 signFunc(-1) = -1

提示:

  • 1 <= nums.length <= 1000
  • -100 <= nums[i] <= 100

解答

方法一:模拟

根据题目要求模拟即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int arraySign(int[] nums) {
int res = 1;
for (int i = 0; i < nums.length; ++i) {
if (nums[i] < 0) {
res *= -1;
} else if (nums[i] == 0) {
return 0;
}
}
return res;
}
}
  • 时间复杂度\(O(N)\),其中 N 为数组 nums 的长度。

  • 空间复杂度\(O(1)\)

每题一图


LC 1822.Sign of the Product of an Array
https://chen-huaneng.github.io/2024/01/10/2024-1-10-2024-01-10-lc-1822/
作者
Abel
发布于
2024年1月10日
更新于
2024年1月10日
许可协议