当前位置:网站首页>力扣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;
}
}边栏推荐
- [kali-information collection] (1.8) ARP reconnaissance tool _Netdiscover
- npm run serve启动报错npm ERR Missing script “serve“
- Challenge LeetCode1000 questions in 365 days - Day 047 Design Circular Queue Circular Queue
- Excel dynamic chart production
- ansible模块--copy模块
- Create your own app applet ecosystem with applet containers
- 云原生(三十) | Kubernetes篇之应用商店-Helm介绍
- SQLAlchemy使用教程
- 打破千篇一律,DIY属于自己独一无二的商城
- 暑期总结3
猜你喜欢

【Acunetix-Forgot your password】

【kali-信息收集】(1.9)Metasploit+搜索引擎工具Shodan

Crack detection technology based on deep learning

sqli-labs(less-11)

【MySQL系列】- LIKE查询 以%开头一定会让索引失效吗

STM32+MPU6050 Design Portable Mini Desktop Clock (Automatically Adjust Time Display Direction)

sva 断言资料

华为eNSP(基础实验通信)

免费的中英文翻译软件-自动批量中英文翻译软件推荐大全

C#/VB.NET to add more lines more columns image watermark into the Word document
随机推荐
ssm web page access database data error
Nanny Level Tutorial: Write Your Own Mobile Apps and Mini Programs (Part 2)
8大软件供应链攻击事件概述
SQL 经典50题(题目+解答)(1)
Coroutines and Lifecycle in Kotlin
Deep Learning 100 Examples - Convolutional Neural Network (CNN) for mnist handwritten digit recognition
AQS-AbstractQueuedSynchronizer
【MySQL】多表联合查询、连接查询、子查询「建议收藏」
企业级数据治理工作怎么开展?Datahub这样做
Camera Hal OEM模块 ---- cmr_snapshot.c
yolo格式(txt)数据集转VOC(xml)
看我如何用多线程,帮助运营小姐姐解决数据校对系统变慢!
Mysql事务隔离级别与MVCC(多版本并发控制)
QT笔记——QT类反射机制简单学习
idea常用插件
AQS-AbstractQueuedSynchronizer
ansible module --yum module
go语言的接口
What is the future of smartwatches?
QT笔记——在一个窗口上显示另外一个透明窗口