public static void main(String[] args) {
int[] nums = {-4,-1,0,3,10};
System.out.println(sortedSquares(nums));
}
public static int[] sortedSquares(int[] nums) {
int length = nums.length;
int negative = -1;
for(int i=0;i<length;i++){
int num = nums[i];
if(num<0){
negative = i;
} else {
break;
}
}
int left = negative;//左边边界
int right = negative+1;//右边边界
int[] ans = new int[length];
int index = 0;
while(left >= 0 || right <= (length-1)){
if(left<0){ // 一旦左边到头了,直接把右边的数据添加进去
ans[index] = nums[right]*nums[right];
right = right+1;
} else if(right > length-1) { // 一旦右边到头了,直接把左边的数据添加进去
ans[index] = nums[left]*nums[left];
left = left-1;
}else {
int leftNum = nums[left]*nums[left];
int rightNum = nums[right]*nums[right];
if(leftNum <= rightNum){ // 判断左右大小
left = left-1;
ans[index] = leftNum;
} else if(leftNum > rightNum) {
right = right+1;
ans[index] = rightNum;
}
}
index++;
}
return ans;
}
```
双指针算法
最新推荐文章于 2024-08-13 14:56:59 发布