LeetCode 题解工作台

数组元素积的符号

已知函数 signFunc(x) 将会根据 x 的正负返回特定值: 如果 x 是正数,返回 1 。 如果 x 是负数,返回 -1 。 如果 x 是等于 0 ,返回 0 。 给你一个整数数组 nums 。令 product 为数组 nums 中所有元素值的乘积。 返回 signFunc(product…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·数学

bolt

答案摘要

题目要求返回数组元素乘积的符号,即正数返回 ,负数返回 , 等于 则返回 。 我们可以定义一个答案变量 `ans`,初始值为 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

已知函数 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
lightbulb

解题思路

方法一:直接遍历

题目要求返回数组元素乘积的符号,即正数返回 11,负数返回 1-1, 等于 00 则返回 00

我们可以定义一个答案变量 ans,初始值为 11

然后遍历数组每个元素 vv,如果 vv 为负数,则将 ans 乘上 1-1,如果 vv00,则提前返回 00

遍历结束后,返回 ans 即可。

时间复杂度 O(n)O(n),其中 nn 为数组长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
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
speed

复杂度分析

指标
时间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)
psychology

面试官常问的追问

外企场景
  • 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?

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

数组元素积的符号题解:数组·数学 | LeetCode #1822 简单