LeetCode 题解工作台
有序数组的平方
给你一个按 非递减顺序 排序的整数数组 nums ,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。 示例 1: 输入: nums = [-4,-1,0,3,10] 输出: [0,1,9,16,100] 解释: 平方后,数组变为 [16,1,0,9,100] 排序后,数组变为 [0,…
3
题型
7
代码语言
3
相关题
当前训练重点
简单 · 双·指针·invariant
答案摘要
由于数组 已经按照非递减顺序排好序,所以数组中负数的平方值是递减的,正数的平方值是递增的。我们可以使用双指针,分别指向数组的两端,每次比较两个指针指向的元素的平方值,将较大的平方值放入结果数组的末尾。 时间复杂度 ,其中 是数组 的长度。忽略答案数组的空间消耗,空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
给你一个按 非递减顺序 排序的整数数组 nums,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。
示例 1:
输入:nums = [-4,-1,0,3,10] 输出:[0,1,9,16,100] 解释:平方后,数组变为 [16,1,0,9,100] 排序后,数组变为 [0,1,9,16,100]
示例 2:
输入:nums = [-7,-3,2,3,11] 输出:[4,9,9,49,121]
提示:
1 <= nums.length <= 104-104 <= nums[i] <= 104nums已按 非递减顺序 排序
进阶:
- 请你设计时间复杂度为
O(n)的算法解决本问题
解题思路
方法一:双指针
由于数组 已经按照非递减顺序排好序,所以数组中负数的平方值是递减的,正数的平方值是递增的。我们可以使用双指针,分别指向数组的两端,每次比较两个指针指向的元素的平方值,将较大的平方值放入结果数组的末尾。
时间复杂度 ,其中 是数组 的长度。忽略答案数组的空间消耗,空间复杂度 。
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
ans = []
i, j = 0, len(nums) - 1
while i <= j:
a = nums[i] * nums[i]
b = nums[j] * nums[j]
if a > b:
ans.append(a)
i += 1
else:
ans.append(b)
j -= 1
return ans[::-1]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for clarity in how the candidate explains the two-pointer method and its impact on the algorithm's time complexity.
- question_mark
The ability to optimize space usage while maintaining linear time is crucial.
- question_mark
Pay attention to how well the candidate understands the failure mode of directly sorting the squared elements.
常见陷阱
外企场景- error
Failing to maintain the two-pointer invariant, which may lead to incorrect results or inefficient solutions.
- error
Incorrectly using extra space for sorting the squared numbers, which can lead to an O(n log n) time complexity.
- error
Not handling edge cases, such as arrays with a single element or all non-negative numbers.
进阶变体
外企场景- arrow_right_alt
Modify the approach to work in-place without using extra space for a result array.
- arrow_right_alt
Handle arrays with both positive and negative numbers, ensuring that the squares are correctly placed in non-decreasing order.
- arrow_right_alt
Adapt the solution to work with larger inputs by considering more efficient memory management.