当前位置:网站首页>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;}}
边栏推荐
猜你喜欢
Getting Started with Three.JS Programmatic Modeling
免费的中英文翻译软件-自动批量中英文翻译软件推荐大全
sva assertion data
字母交换--字符串dp
What is the future of smartwatches?
解决anaconda下载pytorch速度极慢的方法
看我如何用多线程,帮助运营小姐姐解决数据校对系统变慢!
Nanny Level Tutorial: Write Your Own Mobile Apps and Mini Programs (Part 2)
Create a devops CI/CD process using the kubesphere GUI
Failed to configure mysql, what's going on?
随机推荐
Shell编程案例
细学常用类,集合类,IO流
阿苹的思考
划分训练集,验证集,测试集
DTG-SSOD:最新半监督检测框架,Dense Teacher(附论文下载)
雷克萨斯,锁死的安全,挡不住的心寒
Axure谷歌浏览器扩展程序下载及安装方法(免翻墙)
基于深度学习的裂缝检测技术
QAbstractScrollArea、QScrollArea
QT笔记——在一个窗口上显示另外一个透明窗口
QT笔记——Q_PROPERTY了解
go源码之sync.Waitgroup
LeetCode笔记:Weekly Contest 304
jacoco的学习以及理解
注意力机制
SQL 经典50题(题目+解答)(1)
Pytorch 占用cpu资源过多
AdguardHome如何配置设置?我的AdguardHome配置内容过滤器拦截列表
Metaverse "Drummer" Unity: Crazy expansion, suspense still exists
LeetCode第三题(Longest Substring Without Repeating Characters)三部曲之一