当前位置:网站首页>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;}}
边栏推荐
猜你喜欢
【kali-信息收集】(1.9)Metasploit+搜索引擎工具Shodan
When not to use () instead of Void in Swift
Multithreading (Basic) - 40,000 word summary
What is the future of smartwatches?
Nanny Level Tutorial: Write Your Own Mobile Apps and Mini Programs (Part 2)
jacoco的学习以及理解
How to connect TDengine through DBeaver?
sva 断言资料
使用mosquitto过程中的问题解决
Axure谷歌浏览器扩展程序下载及安装方法(免翻墙)
随机推荐
Swift中什么时候不能用 () 代替 Void 来使用
21 Days Learning Challenge - Day 1 Punch (Screen Density)
leetcode: 200. Number of islands
Shell编程之条件语句
字母交换--字符串dp
The exchange - string dp
JSP中如何正确的填写include指令中的file路径呢?
SQL function TRIM
MySQL主从复制几个重要的启动选项
Create a devops CI/CD process using the kubesphere GUI
Jest 测试框架 beforeEach 的设计原理解析
8大软件供应链攻击事件概述
学习经验分享之七:YOLOv5代码中文注释
翁恺C语言程序设计网课笔记合集
ssm网页访问数据库数据报错
go语言的接口
npm run dev 和 npm run serve区别
注意力机制
OLED的HAL库代码介绍及使用(stm32f1/I2C/HAL库版/100%一次点亮)
LeetCode第三题(Longest Substring Without Repeating Characters)三部曲之一