Leetcode第1822题:数组元素积的符号(Sign of product of an array)

解题思路

一个数组所有元素的乘积为正返回1,为零返回0,为负返回-1.
变量pos统计正元素的个数,变量neg统计负元素的个数,遍历数组。
遍历过程中如果有元素为零,直接返回0;遍历结束后,计算neg的个数,奇数就说明所有元素乘积为负,返回-1,否则返回1

核心代码如下:

class Solution {
public:
    int arraySign(vector<int>& nums) {
        int posNum, negNum = 0;
        for (int i=0; i < nums.size(); i++) {
            if (nums[i] == 0) {
                return 0;
            }
            else if (nums[i] < 0) {
                negNum++;
            }
            else {
                posNum++;
            }
        }
        if (negNum%2 == 1)
        {
            return -1;
        }
        else {
            return 1;
        }
        
    }
};
posted @ 2022-10-27 18:17  hql5  阅读(43)  评论(0)    收藏  举报