977. 有序数组的平方
作者:互联网
理解
比较数组两端的元素,一定能比较出一个最大的数字
代码
class Solution {
public int[] sortedSquares(int[] nums) {
int left=0,
right = nums.length - 1;
int[] resultArr = new int[nums.length];
int resIdx = nums.length-1;
while (left <= right) {
int leftVal = getPowDouble(nums[left]);
int rightVal = getPowDouble(nums[right]);
if (leftVal > rightVal) {
resultArr[resIdx--] = leftVal;
++left;
} else {
resultArr[resIdx--] = rightVal;
--right;
}
}
return resultArr;
}
public int getPowDouble(int a) {
return a*a;
}
}
标签:977,平方,nums,int,--,length,resultArr,数组,resIdx 来源: https://www.cnblogs.com/jarico/p/16691362.html