1. 题目
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/1183d10db948731c951c1cffbb5db83f.png)
2. 思路
(1) 双指针法
- 首先找到最小元素的下标,然后令left向左遍历,right向右遍历,依次向新数组中加入较小的值。
- 若一个指针先到达边界,则将另一个指针之后的元素直接加入新数组即可。
(2) 双指针法优化
- 与(1)的思想基本相同,(1)是从内向外依次找到较小值,也可以从外向内依次找到较大值,然后倒序加入新数组,这样省去了找最小元素下标的时间。
3. 代码
public class Test {
public static void main(String[] args) {
Solution solution = new Solution();
int[] ints = solution.sortedSquares(new int[]{-4, -1, 0, 3, 10});
for (int anInt : ints) {
System.out.println(anInt);
}
}
}
class Solution {
public int[] sortedSquares(int[] nums) {
int minIndex = 0;
nums[0] = nums[0] * nums[0];
for (int i = 1; i < nums.length; i++) {
nums[i] = nums[i] * nums[i];
if (nums[i] < nums[i - 1]) {
minIndex = i;
}
}
int[] res = new int[nums.length];
res[0] = nums[minIndex];
int index = 1;
int left = minIndex - 1;
int right = minIndex + 1;
while (left >= 0 && right <= nums.length - 1) {
if (nums[left] < nums[right]) {
res[index++] = nums[left--];
} else {
res[index++] = nums[right++];
}
}
if (right == nums.length) {
while (index < nums.length) {
res[index++] = nums[left--];
}
} else {
while (index < nums.length) {
res[index++] = nums[right++];
}
}
return res;
}
}
class Solution1 {
public int[] sortedSquares(int[] nums) {
int[] res = new int[nums.length];
int left = 0;
int right = nums.length - 1;
int index = nums.length - 1;
int leftValue;
int rightValue;
while (index >= 0) {
leftValue = nums[left] * nums[left];
rightValue = nums[right] * nums[right];
if (leftValue > rightValue) {
res[index--] = leftValue;
left++;
} else {
res[index--] = rightValue;
right--;
}
}
return res;
}
}