Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 52b773f

Browse files
[新增] 新增题目 1822. 数组元素积的符号
1 parent e747a93 commit 52b773f

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-0
lines changed

‎src/1822_signOfTheProductOfAnArray.ts

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
1822. 数组元素积的符号
3+
https://leetcode.cn/problems/sign-of-the-product-of-an-array/
4+
难度:简单
5+
6+
已知函数 signFunc(x) 将会根据 x 的正负返回特定值:
7+
8+
如果 x 是正数,返回 1 。
9+
如果 x 是负数,返回 -1 。
10+
如果 x 是等于 0 ,返回 0 。
11+
给你一个整数数组 nums 。令 product 为数组 nums 中所有元素值的乘积。
12+
13+
返回 signFunc(product) 。
14+
15+
示例 1:
16+
输入:nums = [-1,-2,-3,-4,3,2,1]
17+
输出:1
18+
解释:数组中所有值的乘积是 144 ,且 signFunc(144) = 1
19+
20+
示例 2:
21+
输入:nums = [1,5,0,2,-3]
22+
输出:0
23+
解释:数组中所有值的乘积是 0 ,且 signFunc(0) = 0
24+
25+
示例 3:
26+
输入:nums = [-1,1,-1,1,-1]
27+
输出:-1
28+
解释:数组中所有值的乘积是 -1 ,且 signFunc(-1) = -1
29+
30+
提示:
31+
1 <= nums.length <= 1000
32+
-100 <= nums[i] <= 100
33+
*/
34+
35+
/**
36+
* 判断乘积结果
37+
* + LeetCode 入口
38+
* @param {number[]} nums - 整数数组
39+
* @return {1 | 0 | -1} 乘积结果
40+
*/
41+
function arraySign (nums: number[]): number {
42+
if (nums.includes(0)) return 0
43+
// 先假设乘积为正数
44+
let isPositive = true
45+
for (const num of nums) {
46+
// 遇到负数时切换乘积结果是否为正数
47+
if (num < 0) isPositive = !isPositive
48+
}
49+
return isPositive ? 1 : -1
50+
}
51+
52+
export { arraySign }
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { describe, test, expect } from '@jest/globals'
2+
import testCases from './testCases/1822_signOfTheProductOfAnArray'
3+
import { arraySign } from '../src/1822_signOfTheProductOfAnArray'
4+
5+
describe('1822. Sign of the Product of an Array', () => {
6+
testCases.forEach((testCase, index) => {
7+
test(`Test case index: ${index}`, () => {
8+
expect(arraySign(testCase.input)).toBe(testCase.expected)
9+
})
10+
})
11+
})
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
export default [
2+
{ input: [-1, -2, -3, -4, 3, 2, 1], expected: 1 },
3+
{ input: [1, 5, 0, 2, -3], expected: 0 },
4+
{ input: [-1, 1, -1, 1, -1], expected: -1 }
5+
]

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /