当前位置:网站首页>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;}}
边栏推荐
猜你喜欢
ssm web page access database data error
企业级数据治理工作怎么开展?Datahub这样做
C#为listview选中的项添加右键菜单
10份重磅报告 — 展望中国数字经济未来
Nanny Level Tutorial: Write Your Own Mobile Apps and Mini Programs (Part 2)
CCF论文会议 IEEE 如何查询某个会议期刊的所有文章
喜迎八一 《社会企业开展应聘文职人员培训规范》团体标准出版发行会暨橄榄枝大课堂上线发布会在北京举行
使用kubesphere图形界面创建一个devops的CI/CD流程
JVM简介
The exchange - string dp
随机推荐
借小程序容器打造自有App小程序生态
Thymeleaf
基于深度学习的裂缝检测技术
Multithreading (Basic) - 40,000 word summary
Failed to configure mysql, what's going on?
看我如何用多线程,帮助运营小姐姐解决数据校对系统变慢!
【Acunetix-Forgot your password】
故障分析 | 一条 SELECT 语句跑崩了 MySQL ,怎么回事?
npm WARN config global `--global`, `--local` are deprecated. Use `--location解决方案
雷克萨斯,锁死的安全,挡不住的心寒
yolo格式(txt)数据集转VOC(xml)
sva 断言资料
CCF paper conference IEEE how to query all articles of a conference journal
Coroutines and Lifecycle in Kotlin
jvmxmx和xms参数分析(设定优化校准)
10份重磅报告 — 展望中国数字经济未来
当POC遇见RPA:RPA项目顺利实施的关键
QAbstractScrollArea、QScrollArea
基于深度学习的裂缝检测技术
Deep Learning 100 Examples - Convolutional Neural Network (CNN) for mnist handwritten digit recognition