当前位置:网站首页>[leetcode] 977 square of ordered array
[leetcode] 977 square of ordered array
2022-07-02 15:36:00 【Crisp ~】
Here's a button Non decreasing order Sorted array of integers nums, return The square of each number A new array of , According to the requirements Non decreasing order Sort .
Example 1:
Input : nums = [-4,-1,0,3,10]
Output : [0,1,9,16,100]
explain : After square , The array becomes [16,1,0,9,100]
After ordering , The array 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 Pressed Non decreasing order Sort
Advanced :
Please design with a time complexity of O(n) The algorithm solves this problem
# Direct sort
class Solution(object):
def sortedSquares(self, nums):
return sorted(num*num for num in nums)
# Time complexity :O(n \log n)O(nlogn)
# Spatial complexity :O(\log n)O(logn)
# Double pointer
# Because the array sequence is in ascending order , Square is a positive number , So start at both ends , Numbers with large absolute values enter the sequence squared first
class Solution(object):
def sortedSquares(self, nums):
a = 0
b = len(nums)-1
result = []
while a<=b:
if abs(nums[a])>=abs(nums[b]):
result.append(nums[a]*nums[a])
a+=1
else:
result.append(nums[b]*nums[b])
b-=1
return result[::-1]
边栏推荐
- Bing. Com website
- Leetcode skimming -- verifying the preorder serialization of binary tree # 331 # medium
- 损失函数与正负样本分配:YOLO系列
- 14_Redis_乐观锁
- 基于RZ/G2L | OK-G2LD-C开发板存储读写速度与网络实测
- Application of CDN in game field
- 【LeetCode】876-链表的中间结点
- 10_ Redis_ geospatial_ command
- LeetCode刷题——奇偶链表#328#Medium
- Case introduction and problem analysis of microservice
猜你喜欢
随机推荐
【LeetCode】283-移动零
Pytorch 保存tensor到.mat文件
How to solve the problem of database content output
02.面向容器化后,必须面对golang
15_Redis_Redis.conf详解
Force deduction solution summary 2029 stone game IX
18_ Redis_ Redis master-slave replication & cluster building
【Leetcode】167-两数之和II -输入有序数组
Tidb data migration tool overview
There are 7 seats with great variety, Wuling Jiachen has outstanding product power, large humanized space, and the key price is really fragrant
04.进入云原生后的企业级应用构建的一些思考
11_Redis_Hyperloglog_命令
Practice of compiling principle course -- implementing an interpreter or compiler of elementary function operation language
Loss function and positive and negative sample allocation: Yolo series
MD5加密
05_ queue
17_Redis_Redis发布订阅
. Solution to the problem of Chinese garbled code when net core reads files
【LeetCode】1140-石子游戏II
13_ Redis_ affair