zoukankan      html  css  js  c++  java
  • leetcode 1822. 数组元素积的符号

    已知函数 signFunc(x) 将会根据 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

    法一: 自己的小破码

    class Solution {
    public:
        int arraySign(vector<int>& nums) {
            int ans = 1, cnt = 0;
            for(auto &i:nums){
                //ans *= i;  成功的掉坑了   溢出了
                if(i == 0) ans = 0;
                else if(i<0) cnt++;
            }
            if(ans == 0) return 0;
            else if(cnt %2 == 1) return -1;
            return 1;
        }
    };

    法二: 题解区秀解

    1. 遇 0 返回 0
    2. 正数 * 1
    3. 负数 * -1
    class Solution {
    public:
        int arraySign(vector<int>& nums) {
            int ans = 1;
            for (auto n : nums) {
                if (n == 0) return 0;
                ans *= (n > 0) ? 1 : -1;
            }
            return ans;
        }
    };
    
    作者:ikaruga
    链接:https://leetcode-cn.com/problems/sign-of-the-product-of-an-array/solution/sign-of-the-product-of-an-array-by-ikaru-mxyo/
    来源:力扣(LeetCode)
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

    所有题目都值得学习,认真思考的话,简单题也很有料!

  • 相关阅读:
    SQL跨服查询
    SQL时间函数
    MFC控件添加变量,control和value的区别
    error LNK2001 unresolved external symbol
    VS中C++代码折叠
    ERROR 2003 (HY000): Can't connect to MySQL server
    vs2012换肤功能,vs2012主题及自定义主题
    MFC、SDK和API有什么区别
    寻找子字符串int find_substr(char *s1, char *s2)
    document.title 跑马灯效果
  • 原文地址:https://www.cnblogs.com/AbsolutelyPerfect/p/14699312.html
Copyright © 2011-2022 走看看