LeetCode 题解工作台
数组元素积的符号
已知函数 signFunc(x) 将会根据 x 的正负返回特定值: 如果 x 是正数,返回 1 。 如果 x 是负数,返回 -1 。 如果 x 是等于 0 ,返回 0 。 给你一个整数数组 nums 。令 product 为数组 nums 中所有元素值的乘积。 返回 signFunc(product…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·数学
答案摘要
题目要求返回数组元素乘积的符号,即正数返回 ,负数返回 , 等于 则返回 。 我们可以定义一个答案变量 `ans`,初始值为 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
已知函数 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
解题思路
方法一:直接遍历
题目要求返回数组元素乘积的符号,即正数返回 ,负数返回 , 等于 则返回 。
我们可以定义一个答案变量 ans,初始值为 。
然后遍历数组每个元素 ,如果 为负数,则将 ans 乘上 ,如果 为 ,则提前返回 。
遍历结束后,返回 ans 即可。
时间复杂度 ,其中 为数组长度。空间复杂度 。
class Solution:
def arraySign(self, nums: List[int]) -> int:
ans = 1
for v in nums:
if v == 0:
return 0
if v < 0:
ans *= -1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) since every element is examined once. Space complexity is O(1) because only a counter and a loop variable are used, avoiding full product computation. |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Will you multiply all numbers directly or track signs?
- question_mark
How do you handle zeros in the array efficiently?
- question_mark
Can you solve this with a single pass and constant space?
常见陷阱
外企场景- error
Multiplying all numbers can overflow and is unnecessary for determining the sign.
- error
Forgetting to return 0 immediately when a zero exists in nums.
- error
Incorrectly counting negative numbers or mishandling even/odd counts.
进阶变体
外企场景- arrow_right_alt
Compute sign for floating-point arrays with rounding considerations.
- arrow_right_alt
Find the sign of the product for a subarray defined by given indices.
- arrow_right_alt
Return an array of signs for cumulative products from the start to each index.