当前位置:网站首页>力扣977-有序数组的平方——暴力法&双指针法
力扣977-有序数组的平方——暴力法&双指针法
2022-08-02 11:41:00 【张怼怼√】
题目描述
给你一个按 非递减顺序 排序的整数数组 nums,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。
求解思路
暴力法
遍历数组nums,并将每个元素的平方保存在新建的数组变量arr中;
对arr进行升序排序;
返回arr。
双指针法
- 创建两个指针变量first last,分别指向nums的首部和尾部;
- 每次比较两个变量所指向的元素的数值平方大小,将较大的存放在arr的高位。
输入输出示例

代码
暴力法
class Solution {
public int[] sortedSquares(int[] nums) {
int len = nums.length;
int[] arr = new int[len];
for(int i = 0; i < len; i++){
arr[i] = nums[i] * nums[i];
}
Arrays.sort(arr);
return arr;
}
}双指针法
class Solution {
public int[] sortedSquares(int[] nums) {
int len = nums.length;
int[] arr = new int[len];
int first = 0, last = len-1;
for(int i = len-1; i >= 0; i--){
if(nums[first]*nums[first] >= nums[last]*nums[last]){
arr[i] = nums[first]*nums[first];
first++;
}else{
arr[i] = nums[last]*nums[last];
last--;
}
}
return arr;
}
}边栏推荐
- find查找多类型结尾文件
- C#/VB.NET to add more lines more columns image watermark into the Word document
- STM32+MPU6050 Design Portable Mini Desktop Clock (Automatically Adjust Time Display Direction)
- 喜迎八一 《社会企业开展应聘文职人员培训规范》团体标准出版发行会暨橄榄枝大课堂上线发布会在北京举行
- 网站自动翻译-网站批量自动翻译-网站免费翻译导出
- excel 批量翻译-excel 批量函数公司翻译大全免费
- leetcode: 200. Number of islands
- Running yum reports Error: Cannot retrieve metalink for reposit
- go源码之sync.Waitgroup
- MP的几种查询方式
猜你喜欢
随机推荐
excel 批量翻译-excel 批量函数公司翻译大全免费
Create an application operation process using the kubesphere GUI
SQL function $TRANSLATE
Challenge LeetCode1000 questions in 365 days - Day 047 Design Circular Queue Circular Queue
List排序 ,取最大值最小值
匹配滤波(四种滤波器的幅频特性)
openresty 性能优化
Deep Learning 100 Examples - Convolutional Neural Network (CNN) for mnist handwritten digit recognition
半夜赶工制作简报的我好想说 : 确定了,最终稿就是这样
WPF 实现窗体抖动效果
JSP中include指令的功能简介说明
Create your own app applet ecosystem with applet containers
Breaking the Boundary, Huawei's Storage Journey
FinClip | 来了, 2022 年 7 月更新大盘点
When not to use () instead of Void in Swift
细学常用类,集合类,IO流
Camera Hal OEM模块 ---- cmr_snapshot.c
数字化转型中的低代码
[kali-information collection] (1.8) ARP reconnaissance tool _Netdiscover
The sitcom "Re-Walking the Long March" was staged









