LeetCode-1822. 数组元素积的符号【数组,数字】
2023-09-14 09:01:27 时间
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
该题力扣
解题思路一:判断数组中负元素的个数,偶数个返回1,奇数个返回-1,遇到0元素直接返回0;
class Solution {
public:
int arraySign(vector<int>& nums) {
bool flag=true;
for(auto num:nums){
if(num>0) continue;
if(num==0) return 0;
if(num<0) flag=!flag;
}
return flag?1:-1;
}
};
时间复杂度:O(n)
空间复杂度:O(1)
解题思路二:简化一
class Solution {
public:
int arraySign(vector<int>& nums) {
bool flag=true;
for(auto n:nums){
if(n==0) return 0;
flag=(n>0)?flag:!flag;
}
return flag?1:-1;
}
};
时间复杂度:O(n)
空间复杂度:O(1)
解题思路三:简化二
class Solution {
public:
int arraySign(vector<int>& nums) {
int sign=1;
for(auto n:nums){
if(n==0) return 0;
if(n<0) sign=-sign;
}
return sign;
}
};
时间复杂度:O(n)
空间复杂度:O(1)
相关文章
- LeetCode每日一题-3:回文链表
- ☆打卡算法☆LeetCode 220. 存在重复元素 III 算法解析
- <leetcode刷题-数组> 【双指针】旋转数组
- leetcode-剑指offer59-I 滑动窗口的最大值
- LeetCode每日一题06-13
- LeetCode周赛300,没能AK,刚拿到的勋章要没了……
- leetcode-26删除有序数组中的重复项(双指针)「建议收藏」
- leetcode-792匹配子序列的单词数(桶)
- Leetcode 题目927-三等分0和1组成的数组
- LeetCode 刷题笔记——day 3
- LeetCode 88. 合并两个有序数组
- LeetCode 867. 转置矩阵
- LeetCode笔记:Biweekly Contest 89
- 前端工程师leetcode算法面试必备-简单的二叉树
- LeetCode-题库(8-9)
- leetcode 记录
- LeetCode题解——数组篇
- JavaScript刷LeetCode拿offer-js版字典
- leetcode:合并两个有序数组
- 【leetcode 206】 反转链表(简单)
- 每日一道leetcode:4. 寻找两个正序数组的中位数
- leetcode每日一练:旋转数组
- LeetCode每日一练:数组形式的整数加法