比较数组两端的元素,一定能比较出一个最大的数字
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; } }