数组4、有序数组的平方
给你一个按 非递减顺序 排序的整数数组 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]
出处:https://leetcode-cn.com/problems/squares-of-a-sorted-array/
一、暴力解法:直接将数组进行平方,然后再用自带的排序方法进行排序即可
class Solution {
public int[] sortedSquares(int[] nums) {
int[] rst = new int[nums.length];
for(int i = 0; i<nums.length; i++){
rst[i] = nums[i] * nums[i];
}
Arrays.sort(rst);
return rst;
}
}
二、双指针法
因为给定的数组是非递减的,只不过会有负数存在,平方之后可能会变大,所以最大的肯定是在两侧,依次往里递减,所以就从两边开始,两头进行比较,谁的平方大就存入,然后大的一方继续移动,与之前的小的进行比较,再存入大的,依次循环进行下去。
class Solution {
public int[] sortedSquares(int[] nums) {
int[] rst = new int[nums.length];
int k = rst.length-1;
int i = 0;
int j;
for(j = nums.length - 1; i <= j;){
if(nums[i] * nums[i] < nums[j] * nums[j]){
rst[k--] = nums[j]*nums[j];
j--;
}else{
rst[k--] = nums[i] * nums[i];
i++;
}
}
return rst;
}
}