/**
* 977. 有序数组的平方
* @author wsq
* @date 2020/10/17
给定一个按非递减顺序排序的整数数组 A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。
示例 1:
输入:[-4,-1,0,3,10]
输出:[0,1,9,16,100]
示例 2:
输入:[-7,-3,2,3,11]
输出:[4,9,9,49,121]
链接:https://leetcode-cn.com/problems/squares-of-a-sorted-array
*/
package com.wsq.sort;
public class SortedSquares {
/**
* 由于原数组时非递减的数组,因此,平方大的在数组两端
* 所以采用左右双指针的形式遍历数组,并新生成一个数组存储平方值
* @param A
* @return
*/
public int[] sortedSquares(int[] A) {
int n = A.length;
if(n == 0){
return A;
}
int[] ans = new int[n];
int left = 0;
int right = n - 1;
int pos = n-1;
while(left <= right){
int tmpRight = A[right] * A[right];
int tmpLeft = A[left] * A[left];
if(tmpRight > tmpLeft){
ans[pos--] = tmpRight;
right--;
}else{
ans[pos--] = tmpLeft;
left++;
}
}
return ans;
}
}
977. 有序数组的平方
最新推荐文章于 2021-02-06 21:38:53 发布