Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
采取双指针,同时比较两侧的正负及大小。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| class Solution { public int[] sortedSquares(int[] nums) { int left = 0; int right = nums.length - 1; int i = nums.length-1; int[] ans = new int[nums.length]; while (left <= right) { if ( nums[left] < 0 ){ if ( (-nums[left]) < nums[right] ){ ans[i] = nums[right] * nums[right]; right--; } else { ans[i] = nums[left] * nums[left]; left++; } i--; } else{ if ( nums[left] < nums[right] ){ ans[i] = nums[right] * nums[right]; right--; } else{ ans[i] = nums[left] * nums[left]; left++; } i--; } } return ans; } }
|