思路
如果数组中存在 0:乘积一定为 0,直接返回 0。
统计负数的个数:
负数个数为偶数 → 乘积为正 → 返回 1。
负数个数为奇数 → 乘积为负 → 返回 -1。
解题过程
一开始算了所有的积,但是提交时测试没通过,后来发现这个题目真的没必要把数组所有数的乘积算出来,判断乘积符号就可以了。
复杂度
时间复杂度: O(n)
空间复杂度: O(1)
核心代码
cpp
class Solution {
public:
int signFunc(int x){
if(x>0){
return 1;
}else if(x<0){
return -1;
}else{
return 0;
}
}
int arraySign(vector<int>& nums) {
int n=nums.size();
int count_neg=0;
for(int i=0;i<n;i++){
if(nums[i]<0){// 统计负数个数
count_neg++;
}else if(nums[i]==0){// 有0,乘积为0
return 0;
}
}
// 根据负数个数的奇偶性返回结果
return (count_neg%2==0)?1:-1;
}
};