当前位置:网站首页>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;}}
边栏推荐
猜你喜欢
随机推荐
翻译英语的软件-免费翻译软件-各种语言互相翻译
【项目管理技术的优势】
jvmxmx和xms参数分析(设定优化校准)
企业级数据治理工作怎么开展?Datahub这样做
Problem solving in the process of using mosquitto
基于threejs的商品VR展示平台的设计与实现思路
QT笔记——QT类反射机制简单学习
When not to use () instead of Void in Swift
Crack detection technology based on deep learning
AQS-AbstractQueuedSynchronizer
Coroutines and Lifecycle in Kotlin
免费的中英文翻译软件-自动批量中英文翻译软件推荐大全
匹配滤波(四种滤波器的幅频特性)
ABAP-OOAVL模板程序
Oracle降低高水位
Oracle 19c 连接PDB
go语言的接口
SQL(面试实战07)
find查找多类型结尾文件
LeetCode笔记:Weekly Contest 304