当前位置:网站首页>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;}}边栏推荐
- npm WARN deprecated [email protected] This version of tar is no longer supported, and will not receive
- 小程序插件让开发者受益的几个理由
- Failed to configure mysql, what's going on?
- 观察者(observer)模式(二) —— 实现线程安全的监听器
- 面积曲线AUC(area under curve)
- 受邀出席Rust开发者大会|Rust如何助力量化高频交易?
- 字母交换--字符串dp
- QListView的使用
- go语言的接口
- 故障分析 | 一条 SELECT 语句跑崩了 MySQL ,怎么回事?
猜你喜欢

华为eNSP(基础实验通信)

C#为listview选中的项添加右键菜单

面积曲线AUC(area under curve)

AQS-AbstractQueuedSynchronizer

雷克萨斯,锁死的安全,挡不住的心寒

CAN总线的AUTOSAR网络管理

Breaking the Boundary, Huawei's Storage Journey

注意力机制

Mysql transaction isolation level and MVCC (multi-version concurrency control)

Getting Started with Three.JS Programmatic Modeling
随机推荐
Question about #oracle#, how to solve it?
匹配滤波(四种滤波器的幅频特性)
JSP中如何正确的填写include指令中的file路径呢?
JVM简介
MySQL主从复制几个重要的启动选项
免费的中英文翻译软件-自动批量中英文翻译软件推荐大全
npm WARN deprecated [email protected] This version of tar is no longer supported, and will not receive
Thymeleaf
【云驻共创】数据工坊平台,0代码开发数据处理业务“快”人一步
数字化转型中的低代码
LeetCode笔记:Weekly Contest 304
ansible module --yum module
Crack detection technology based on deep learning
项目监控六大事项
解决导出excel文件名中文乱码的问题
智能手表前景如何?
npm install报错npm ERR Could not resolve dependency npm ERR peer
5G网络切片技术
Oracle 19c 连接PDB
C#为listview选中的项添加右键菜单