给你一个按 非递减顺序 排序的整数数组 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]
暴解:
class Solution {
public int[] sortedSquares(int[] nums) {
for(int i=0;i<nums.length;i++){
nums[i] *= nums[i];
}
Arrays.sort(nums);
return nums;
}
}
关注点:Arrays类加粗样式里提供了排序、二分查找类的静态方法,非常方便调用
;
空间换时间
class Solution {
public int[] sortedSquares(int[] nums) {
int[] marks = new int[10001];
for(int i=0;i<marks.length;i++){
marks[i] = 0;
}
for(int i=0;i<nums.length;i++){
marks[Math.abs(nums[i])]++;
}
int j=0;
for(int i=0;i<marks.length&&j<nums.length;i++){
while(marks[i] != 0){
nums[j++] = i*i;
marks[i]--;
}
}
return nums;
}
}
双指针法
class Solution {
public int[] sortedSquares(int[] nums) {
int[] result = new int[nums.length];
int head = 0,tail = nums.length - 1;
int i = nums.length - 1;
while(head<=tail){
int rs1 = nums[head]*nums[head];
int rs2 = nums[tail]*nums[tail];
if(rs1<rs2){
result[i--] = rs2;
tail--;
}else{
result[i--] = rs1;
head++;
}
}
return result;
}
}