Easy
题目描述
实现一个函数 signFunc(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
约束条件:
1 <= nums.length <= 1000-100 <= nums[i] <= 100
解题思路
这道题要求我们判断数组中所有元素乘积的符号,但不需要计算具体的乘积值。
核心思路:
- 零值判断:如果数组中包含 0,那么乘积必定为 0,直接返回 0
- 符号统计:乘积的符号只取决于负数的个数
- 负数个数为偶数:乘积为正,返回 1
- 负数个数为奇数:乘积为负,返回 -1
算法步骤:
- 遍历数组,统计负数的个数
- 如果遇到 0,直接返回 0
- 如果负数个数为偶数,返回 1;否则返回 -1
这种方法避免了实际计算乘积可能导致的整数溢出问题,时间复杂度为 O(n),空间复杂度为 O(1)。
其他解法:
- 可以用符号变量记录当前乘积的符号,每遇到一个负数就翻转符号
- 也可以将所有非零元素替换为其符号值(1或-1),然后计算乘积的符号
代码实现
class Solution {
public:
int arraySign(vector<int>& nums) {
int negativeCount = 0;
for (int num : nums) {
if (num == 0) {
return 0;
}
if (num < 0) {
negativeCount++;
}
}
return negativeCount % 2 == 0 ? 1 : -1;
}
};
class Solution:
def arraySign(self, nums: List[int]) -> int:
negative_count = 0
for num in nums:
if num == 0:
return 0
if num < 0:
negative_count += 1
return 1 if negative_count % 2 == 0 else -1
public class Solution {
public int ArraySign(int[] nums) {
int negativeCount = 0;
foreach (int num in nums) {
if (num == 0) {
return 0;
}
if (num < 0) {
negativeCount++;
}
}
return negativeCount % 2 == 0 ? 1 : -1;
}
}
var arraySign = function(nums) {
let negativeCount = 0;
for (let num of nums) {
if (num === 0) return 0;
if (num < 0) negativeCount++;
}
return negativeCount % 2 === 0 ? 1 : -1;
};
复杂度分析
| 复杂度类型 | 复杂度 | 说明 |
|---|---|---|
| 时间复杂度 | O(n) | 需要遍历整个数组一次 |
| 空间复杂度 | O(1) | 只使用了常数级别的额外空间 |