刷题顺序按照代码随想录建议
题目描述
英文版描述
Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
Example 1:
Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Explanation: After squaring, the array becomes [16,1,0,9,100].
Example 2:
Input: nums = [-7,-3,2,3,11]
Output: [4,9,9,49,121]
Constraints:
1 <= nums.length <= 10(4)-10(4) <= nums[i] <= 10(4)numsis sorted in non-decreasing order.
英文版地址
中文版描述
给你一个按 非递减顺序 排序的整数数组 nums,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。
示例 1:
输入: nums = [-4,-1,0,3,10]
输出: [0,1,9,16,100]
解释: 平方后,数组变为 [16,1,0,9,100]
示例 2:
输入: nums = [-7,-3,2,3,11]
输出: [4,9,9,49,121]
提示:
-
1 <= nums.length <= 10(4) -
-10(4) <= nums[i] <= 10(4) -
nums已按 非递减顺序 排序- 非递减顺序简单理解就是是可能有重复元素的递增序列
中文版地址
解题方法
俺这版
class Solution {
public int[] sortedSquares(int[] nums) {
int left = 0;
int right = nums.length - 1;
int[] result = new int[nums.length];
int count = nums.length - 1;
while (left <= right) {
int leftNum = (int) Math.pow(nums[left], 2);
int rightNum = (int) Math.pow(nums[right], 2);
if (leftNum <= rightNum) {
result[count] = rightNum;
right--;
} else {
result[count] = leftNum;
left++;
}
count--;
}
return result;
}
}
复杂度分析
-
时间复杂度:O(n),其中 n 是数组 nums 的长度
-
空间复杂度:O(1)
- 除了存储答案的数组以外,我们需要 O(1)的栈空间进行排序
官方版
方法一:直接排序
class Solution {
public int[] sortedSquares(int[] nums) {
int[] ans = new int[nums.length];
for (int i = 0; i < nums.length; ++i) {
ans[i] = nums[i] * nums[i];
}
Arrays.sort(ans);
return ans;
}
}
复杂度分析
-
时间复杂度:O(nlogn),其中 n 是数组 nums 的长度
-
空间复杂度:O(logn)
-
除了存储答案的数组以外,我们需要 O(logn)的栈空间进行排序
-
方法二:双指针
class Solution {
public int[] sortedSquares(int[] nums) {
int n = nums.length;
int[] ans = new int[n];
for (int i = 0, j = n - 1, pos = n - 1; i <= j;) {
if (nums[i] * nums[i] > nums[j] * nums[j]) {
ans[pos] = nums[i] * nums[i];
++i;
} else {
ans[pos] = nums[j] * nums[j];
--j;
}
--pos;
}
return ans;
}
}
复杂度分析
-
时间复杂度:O(n),其中 n 是数组 nums 的长度
-
空间复杂度:O(1)
- 除了存储答案的数组以外,我们需要 O(1)的栈空间进行排序