当前位置:网站首页>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;}}边栏推荐
- 您应该知道的 Google Sheets 使用技巧
- The exchange - string dp
- Oracle 19c配置ob server
- Hub and Spoke配置案例
- npm WARN deprecated [email protected] This version of tar is no longer supported, and will not receive
- 翻译英语的软件-免费翻译软件-各种语言互相翻译
- Running yum reports Error: Cannot retrieve metalink for reposit
- leetcode: 200. Number of islands
- npm install报错npm ERR Could not resolve dependency npm ERR peer
- sqli-labs(less-11)
猜你喜欢
随机推荐
[kali-information collection] (1.9) Metasploit + search engine tool Shodan
Deep Learning 100 Examples - Convolutional Neural Network (CNN) for mnist handwritten digit recognition
云原生(三十) | Kubernetes篇之应用商店-Helm介绍
【Acunetix-忘记密码】
前男友买辣椒水威胁要抢女儿,女方能否申请人身安全保护令?
【云驻共创】数据工坊平台,0代码开发数据处理业务“快”人一步
中原银行实时风控体系建设实践
Create a devops CI/CD process using the kubesphere GUI
Create an application operation process using the kubesphere GUI
Hub and Spoke配置案例
21 Days Learning Challenge - Day 1 Punch (Screen Density)
Multithreading (Basic) - 40,000 word summary
sqli-labs(less-11)
QT笔记——Q_PROPERTY了解
Jest 测试框架 beforeEach 的设计原理解析
免费的中英文翻译软件-自动批量中英文翻译软件推荐大全
MP的几种查询方式
今日睡眠质量记录85分
Mysql transaction isolation level and MVCC (multi-version concurrency control)
What is the future of smartwatches?









