当前位置:网站首页>Likou 977-Squaring of ordered arrays - brute force method & double pointer method
Likou 977-Squaring of ordered arrays - brute force method & double pointer method
2022-08-02 11:45:00 【Zhang Ran Ran √】
Title description
Given you an array nums of integers sorted in non-decreasing order, returns a new array of squares of each number, requiring alsoSort by non-decreasing order.
Solution ideas
violence laws
traverse the array nums and save the square of each element in the newly created array variable arr;
sort arr in ascending order;
return arr.
Double pointer method
- Create two pointer variables first last, pointing to the head and tail of nums respectively;
- Compare the square values of the elements pointed to by two variables each time, and store the larger one in the high position of arr.
Input and output example

Code
violence laws
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;}}Double pointer method
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;}}边栏推荐
- ansible模块--copy模块
- 【2022 小目标检测综述】Towards Large-Scale Small Object Detection: Survey and Benchmarks
- pyqt5连接MYSQL数据库问题
- Excel dynamic chart production
- Several reasons why applet plugins benefit developers
- QT笔记——QT类反射机制简单学习
- 运行yum报错Error: Cannot retrieve metalink for reposit
- ansible module --copy module
- SQL function $TRANSLATE
- Mysql事务隔离级别与MVCC(多版本并发控制)
猜你喜欢

X86函数调用模型分析

npm run dev 和 npm run serve区别

5G网络切片技术

C#为listview选中的项添加右键菜单

面积曲线AUC(area under curve)
[email protected] This version of tar is no longer supported, and will not receive"/>npm WARN deprecated [email protected] This version of tar is no longer supported, and will not receive

Challenge LeetCode1000 questions in 365 days - Day 047 Design Circular Queue Circular Queue
![[kali-information collection] (1.8) ARP reconnaissance tool _Netdiscover](/img/04/f477cd8726d147b892f6050d46c312.png)
[kali-information collection] (1.8) ARP reconnaissance tool _Netdiscover

10份重磅报告 — 展望中国数字经济未来

免费文档翻译-免费批量文档翻译软件推荐
随机推荐
Several reasons why applet plugins benefit developers
Learning Experience Sharing Seven: YOLOv5 Code Chinese Comments
“纯C”实现——三子棋小游戏
智能手表前景如何?
您应该知道的 Google Sheets 使用技巧
npm run serve启动报错npm ERR Missing script “serve“
MP的几种查询方式
sqli-labs(less-11)
ES2020-23简单易懂又实用的精选特性讲解 日常开发必备干货!
QT笔记——Q_PROPERTY了解
jvmxmx和xms参数分析(设定优化校准)
云原生(三十) | Kubernetes篇之应用商店-Helm介绍
openresty 性能优化
Shell编程之条件语句
QListView的使用
【MySQL系列】- LIKE查询 以%开头一定会让索引失效吗
Multithreading (Basic) - 40,000 word summary
5G网络切片技术
SQL function TRIM
QT笔记——QT类反射机制简单学习