码迷,mamicode.com
首页 > 其他好文 > 详细

1822. Sign of the Product of an Array

时间:2021-05-23 23:06:06      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:function   size   value   color   bsp   turn   returns   tor   nts   

There is a function signFunc(x) that returns:

  • 1 if x is positive.
  • -1 if x is negative.
  • 0 if x is equal to 0.

You are given an integer array nums. Let product be the product of all values in the array nums.

Return signFunc(product).

Example 1:

Input: nums = [-1,-2,-3,-4,3,2,1]
Output: 1
Explanation: The product of all values in the array is 144, and signFunc(144) = 1

Constraints:

  • 1 <= nums.length <= 1000
  • -100 <= nums[i] <= 100
class Solution {
public:
    int arraySign(vector<int>& nums) {
        int cnt_neg=0;
        for(int i=0;i<nums.size();i++){
            if(nums[i]==0)
                return 0;
            if(nums[i]<0)
                cnt_neg++;  
        }
        if(cnt_neg%2==0) return 1;
        else return -1;
    }
};

更好的写法

class Solution {
public:
    int arraySign(vector<int>& nums) {
        int sign=1;
        for(int n:nums){
            if(n==0)
                return 0;
            if(n<0)
                sign=-sign;
        }
        return sign;
    }
};

 

1822. Sign of the Product of an Array

标签:function   size   value   color   bsp   turn   returns   tor   nts   

原文地址:https://www.cnblogs.com/Makerr/p/14727705.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!