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

当POC遇见RPA:RPA项目顺利实施的关键

AQS-AbstractQueuedSynchronizer

MapStruct

sva 断言资料

darknet训练yolov4模型

注意力机制
[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

ssm网页访问数据库数据报错

翻译英语的软件-免费翻译软件-各种语言互相翻译

npm run dev 和 npm run serve区别
随机推荐
匹配滤波(四种滤波器的幅频特性)
SQL 数据更新
ABAP-OOAVL模板程序
智能手表前景如何?
CCF论文会议 IEEE 如何查询某个会议期刊的所有文章
观察者(observer)模式(二) —— 实现线程安全的监听器
面积曲线AUC(area under curve)
pyqt5连接MYSQL数据库问题
企业级数据治理工作怎么开展?Datahub这样做
华为eNSP(基础实验通信)
sva 断言资料
小程序插件让开发者受益的几个理由
基于深度学习的裂缝检测技术
SQL function TRIM
The sitcom "Re-Walking the Long March" was staged
QAbstractScrollArea、QScrollArea
21 Days Learning Challenge - Day 1 Punch (Screen Density)
爆款视频怎么做?这里或许有答案!
【云驻共创】数据工坊平台,0代码开发数据处理业务“快”人一步
Swift中什么时候不能用 () 代替 Void 来使用