Skip to content

Commit 24105c7

Browse files
committed
[新增] 新增题目 977. 有序数组的平方
1 parent ccdf554 commit 24105c7

File tree

3 files changed

+82
-0
lines changed

3 files changed

+82
-0
lines changed

src/977_squaresOfASortedArray.ts

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/*
2+
977. 有序数组的平方
3+
难度:简单
4+
题目链接:https://leetcode.cn/problems/squares-of-a-sorted-array/
5+
6+
给你一个按 非递减顺序 排序的整数数组 nums,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。
7+
8+
示例 1:
9+
输入:nums = [-4,-1,0,3,10]
10+
输出:[0,1,9,16,100]
11+
解释:平方后,数组变为 [16,1,0,9,100]
12+
排序后,数组变为 [0,1,9,16,100]
13+
14+
示例 2:
15+
输入:nums = [-7,-3,2,3,11]
16+
输出:[4,9,9,49,121]
17+
18+
提示:
19+
1 <= nums.length <= 104
20+
-104 <= nums[i] <= 104
21+
nums 已按 非递减顺序 排序
22+
23+
进阶:
24+
请你设计时间复杂度为 O(n) 的算法解决本问题
25+
*/
26+
27+
import { fileURLToPath } from 'url'
28+
import testCases from '../tests/testCases/977_squaresOfASortedArray.js'
29+
30+
/**
31+
* 计算有序数组的平方
32+
* - LeetCode 入口
33+
* @param {number[]} nums - 待计算的非递减顺序排序的整数数组
34+
* @returns {number[]} 非递减顺序排序的整数结果数组
35+
*/
36+
export function sortedSquares (nums: number[]): number[] {
37+
// 初始化返回值
38+
const result: number[] = new Array<number>(nums.length)
39+
40+
// 使用双指针法,从原数组前后向中间遍历
41+
let leftIndex: number = 0
42+
let rightIndex: number = nums.length - 1
43+
let targetIndex: number = nums.length - 1
44+
while (leftIndex <= rightIndex) {
45+
// 计算两个指针所处位置的平方
46+
const leftResult = nums[leftIndex] * nums[leftIndex]
47+
const rightResult = nums[rightIndex] * nums[rightIndex]
48+
49+
// 判断左右两边平方结果的大小,将较大的结果依次从右向左放置在结果数组中
50+
if (leftResult > rightResult) {
51+
result[targetIndex--] = leftResult
52+
leftIndex++
53+
} else {
54+
result[targetIndex--] = rightResult
55+
rightIndex--
56+
}
57+
}
58+
59+
return result
60+
}
61+
62+
// Debug
63+
if (process.argv[1] === fileURLToPath(import.meta.url)) {
64+
const { input, expected } = testCases[0]
65+
const output = sortedSquares(input)
66+
console.log({ input, output, expected })
67+
}
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/977_squaresOfASortedArray.js'
3+
import { sortedSquares } from '../src/977_squaresOfASortedArray.js'
4+
5+
describe('977. Squares of a Sorted Array', () => {
6+
testCases.forEach(({ input, expected }, index) => {
7+
test(`Test case index: ${index}, Input: ${input.toString()}`, () => {
8+
expect(sortedSquares(input)).toEqual(expected)
9+
})
10+
})
11+
})
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
export default [
2+
{ input: [-4, -1, 0, 3, 10], expected: [0, 1, 9, 16, 100] },
3+
{ input: [-7, -3, 2, 3, 11], expected: [4, 9, 9, 49, 121] }
4+
]

0 commit comments

Comments
 (0)