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

jacoco的学习以及理解

数字化转型中的低代码

“纯C”实现——三子棋小游戏

细学常用类,集合类,IO流

华为eNSP(基础实验通信)

使用kubesphere图形界面创建一个应用操作流程

STM32+MPU6050 Design Portable Mini Desktop Clock (Automatically Adjust Time Display Direction)

Deep Learning 100 Examples - Convolutional Neural Network (CNN) for mnist handwritten digit recognition

QAbstractScrollArea、QScrollArea

网站自动翻译-网站批量自动翻译-网站免费翻译导出
随机推荐
SQL function $TRANSLATE
小程序插件的生态丰富,加速开发建设效率
Multithreading (Basic) - 40,000 word summary
阿苹的思考
leetcode: 200. Number of islands
LeetCode笔记:Weekly Contest 304
MapStruct
解决anaconda下载pytorch速度极慢的方法
openresty 性能优化
Metaverse "Drummer" Unity: Crazy expansion, suspense still exists
【kali-信息收集】(1.9)Metasploit+搜索引擎工具Shodan
【kali-信息收集】(1.8)ARP侦查工具_Netdiscover
How to connect TDengine through DBeaver?
数字化转型中的低代码
ansible module --yum module
字母交换--字符串dp
中原银行实时风控体系建设实践
[kali-information collection] (1.8) ARP reconnaissance tool _Netdiscover
npm WARN config global `--global`, `--local` are deprecated. Use `--location解决方案
图形处理单元(GPU)的演进