力扣 977. 有序数组的平方 js
时间: 2023-11-10 18:06:58 浏览: 233
这是一个关于有序数组的平方的问题。给定一个按非递减顺序排序的整数数组,你需要返回每个数字的平方,并按非递减顺序返回新的数组。
下面是一个使用 JavaScript 解决该问题的示例代码:
```javascript
var sortedSquares = function(nums) {
// 创建一个新数组用于存放平方后的结果
var result = [];
var left = 0; // 左指针
var right = nums.length - 1; // 右指针
// 从数组两端开始遍历
while (left <= right) {
var leftSquare = nums[left] * nums[left];
var rightSquare = nums[right] * nums[right];
// 判断左右指针所指元素的平方大小,将较大的平方值添加到结果数组中
if (leftSquare > rightSquare) {
result.unshift(leftSquare);
left++;
} else {
result.unshift(rightSquare);
right--;
}
}
return result;
};
```
通过上述代码,在给定的有序数组上进行双指针遍历,每次取左右指针所指元素的平方,将较大的平方值从结果数组的头部插入。最终返回按非递减顺序排列的平方结果数组。
希望能够帮助到你!如果有任何疑问,请随时提出。
阅读全文
相关推荐
![md](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)