当前位置:网站首页>leetcode--977. Squares of a Sorted Array
leetcode--977. Squares of a Sorted Array
2022-04-23 14:03:00 【Amelia who loves learning】
-
Problem:Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. 1
-
Example :
# Example 1
Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Explanation: After squaring, the array becomes [16,1,0,9,100].
After sorting, it becomes [0,1,9,16,100].
# Example 2
Input: nums = [-7,-3,2,3,11]
Output: [4,9,9,49,121]
- Tips :
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums is sorted in non-decreasing order.
- Ideas :
First, sort each value in the list
Output with built-in sorting algorithm
- Solution 1 – direct :
class Solution:
def sortedSquares(self, nums):
dou_nums = [x * x for x in nums]
return sorted(dou_nums)
- Ideas :
Set an empty list to store qualified values , Set the head and tail pointer to head and tail
When the head pointer is not equal to the tail pointer , Continue operation , If the square of the head is greater than the square of the tail , Insert the header value into the list and add one to the pointer ; If the square of the tail value is greater than or equal to the square of the head value , Insert the square of the tail value into the list and add one to the tail pointer ; If the head pointer is greater than or equal to the tail pointer , And then jump out of the loop
Insert the remaining header values squared into the list
Returns the reverse order of the list
- Solution 2 – Double pointer :
class Solution:
def sortedSquares(self, nums):
dou_nums = []
a, b = 0, len(nums)-1
while a != b:
dou_a = nums[a] ** 2
dou_b = nums[b] ** 2
if dou_a > dou_b:
dou_nums.append(dou_a)
a += 1
elif dou_b >= dou_a:
dou_nums.append(dou_b)
b -= 1
if a >= b:
break
dou_nums.append(nums[a]**2)
return dou_nums[::-1]
source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/squares-of-a-sorted-array ︎
版权声明
本文为[Amelia who loves learning]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231341317276.html
边栏推荐
- Record a strange bug: component copy after cache component jump
- 生产环境——
- 浅谈基于openssl的多级证书,Multi-level CA的签发和管理,以及双向认证
- org.apache.parquet.schema.InvalidSchemaException: A group type can not be empty. Parquet does not su
- 9月8日,临去松山湖的前夜
- JS force deduction brush question 102 Sequence traversal of binary tree
- Quartus Prime硬件实验开发(DE2-115板)实验二功能可调综合计时器设计
- Neuron and neural network
- Pytorch 经典卷积神经网络 LeNet
- Quartus Prime硬件实验开发(DE2-115板)实验一CPU指令运算器设计
猜你喜欢
随机推荐
There is a mining virus in the server
Decentralized Collaborative Learning Framework for Next POI Recommendation
1256:献给阿尔吉侬的花束
微信小程序进行蓝牙初始化、搜索附近蓝牙设备及连接指定蓝牙(一)
Android interview theme collection
容差分析相关的计算公式
分页SQL
金蝶云星空API调用实践
专题测试05·二重积分【李艳芳全程班】
pthread_self()为何重复了
理解虚基类、虚函数与纯虚函数的概念(转)
微信小程序调用客服接口
scikit-learn構建模型的萬能模板
Atcoder beginer contest 248c dice sum (generating function)
switch使用(微信小程序)
基于ibeacons签到系统
websocket
Spark入门基本操作
Go语言 RPC通讯
centOS下mysql主从配置