当前位置:网站首页>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;}}边栏推荐
猜你喜欢

SQL 经典50题(题目+解答)(1)

中原银行实时风控体系建设实践

打破千篇一律,DIY属于自己独一无二的商城

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

看我如何用多线程,帮助运营小姐姐解决数据校对系统变慢!

sva assertion data

观察者(observer)模式(二) —— 实现线程安全的监听器
![[kali-information collection] (1.8) ARP reconnaissance tool _Netdiscover](/img/04/f477cd8726d147b892f6050d46c312.png)
[kali-information collection] (1.8) ARP reconnaissance tool _Netdiscover

喜迎八一 《社会企业开展应聘文职人员培训规范》团体标准出版发行会暨橄榄枝大课堂上线发布会在北京举行

What is the future of smartwatches?
随机推荐
SQL 经典50题(题目+解答)(1)
当POC遇见RPA:RPA项目顺利实施的关键
ansible模块--copy模块
DTG-SSOD:最新半监督检测框架,Dense Teacher(附论文下载)
Camera Hal OEM模块 ---- cmr_snapshot.c
免费文档翻译-免费批量文档翻译软件推荐
打破千篇一律,DIY属于自己独一无二的商城
【MySQL系列】- LIKE查询 以%开头一定会让索引失效吗
翻译英语的软件-免费翻译软件-各种语言互相翻译
Create your own app applet ecosystem with applet containers
SQL函数 TRIM
FinClip | 来了, 2022 年 7 月更新大盘点
面积曲线AUC(area under curve)
When not to use () instead of Void in Swift
pyqt5连接MYSQL数据库问题
npm WARN deprecated [email protected] This version of tar is no longer supported, and will not receive
CCF论文会议 IEEE 如何查询某个会议期刊的所有文章
使用无界队列的线程池会导致内存飙升吗?
10份重磅报告 — 展望中国数字经济未来
腾讯云云函数SCF—入门须知