1822. 数组元素积的符号
1822. 数组元素积的符号
题目
Implement a function signFunc(x) that returns:
1ifxis positive.-1ifxis negative.0ifxis equal to0.
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
Example 2:
Input: nums = [1,5,0,2,-3]
Output: 0
Explanation: The product of all values in the array is 0, and signFunc(0) = 0
Example 3:
Input: nums = [-1,1,-1,1,-1]
Output: -1
Explanation: The product of all values in the array is -1, and signFunc(-1) = -1
Constraints:
1 <= nums.length <= 1000-100 <= nums[i] <= 100
题目大意
已知函数 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
解题思路
处理零的情况:
- 如果数组中有一个 0,那么乘积必然是 0,因此直接返回 0。
负数的个数:
- 由于每个负数都会影响乘积的符号(负负得正),所以我们只关心负数的数量。
- 遍历数组并统计负数的个数。
返回结果:
- 如果负数的个数是偶数,说明乘积是正数,返回
1(正数); - 如果负数的个数是奇数,说明乘积是负数,返回
-1(负数)。
- 如果负数的个数是偶数,说明乘积是正数,返回
复杂度分析
- 时间复杂度:
O(n),其中n是数组的长度。只遍历数组一次来统计负数的个数。 - 空间复杂度:
O(1),只用了常数空间来存储计数器negaCount。
代码
/**
* @param {number[]} nums
* @return {number}
*/
var arraySign = function (nums) {
let negaCount = 0;
for (let num of nums) {
// 如果数组中有 0,返回 0
if (num == 0) return 0;
// 如果是负数,负数计数增加
if (num < 0) {
negaCount++;
}
}
// 如果负数个数是偶数,返回1,否则返回-1
return negaCount % 2 == 0 ? 1 : -1;
};
