当前位置:网站首页>【LeetCode】977-有序数组的平方
【LeetCode】977-有序数组的平方
2022-07-02 12:09:00 【酥酥~】
给你一个按 非递减顺序 排序的整数数组 nums,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。
示例 1:
输入: nums = [-4,-1,0,3,10]
输出: [0,1,9,16,100]
解释: 平方后,数组变为 [16,1,0,9,100]
排序后,数组变为 [0,1,9,16,100]
示例 2:
输入: nums = [-7,-3,2,3,11]
输出: [4,9,9,49,121]
提示:
- 1 <= nums.length <= 104
- -104 <= nums[i] <= 104
- nums 已按 非递减顺序 排序
进阶:
请你设计时间复杂度为 O(n) 的算法解决本问题
#直接排序
class Solution(object):
def sortedSquares(self, nums):
return sorted(num*num for num in nums)
#时间复杂度:O(n \log n)O(nlogn)
#空间复杂度:O(\log n)O(logn)
#双指针
#因为数组序列为升序,平方后都是正数,所以从两端开始,绝对值大的数先平方进入序列
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
- Common English abbreviations for data analysis (I)
- Topology architecture of the minimum deployment of tidb cluster
- 【LeetCode】1254-统计封闭岛屿的数量
- 【网络安全】网络资产收集
- 【LeetCode】1162-地图分析
- 10_ Redis_ geospatial_ command
- 让您的HMI更具优势,FET-G2LD-C核心板是个好选择
- Yolov5 code reproduction and server operation
- 17_Redis_Redis发布订阅
猜你喜欢

How to find a sense of career direction

你不知道的Set集合

Beijing rental data analysis

Download blender on Alibaba cloud image station

How does the computer set up speakers to play microphone sound

FPGA - 7系列 FPGA内部结构之Clocking -03- 时钟管理模块(CMT)

LeetCode刷题——递增的三元子序列#334#Medium

终于搞懂了JS中的事件循环,同步/异步,微任务/宏任务,运行机制(附笔试题)

PTA 天梯赛习题集 L2-001 城市间紧急救援

Leetcode skimming -- sum of two integers 371 medium
随机推荐
Practical debugging skills
Deploy tidb cluster with tiup
百变大7座,五菱佳辰产品力出众,人性化大空间,关键价格真香
Tidb environment and system configuration check
List set & UML diagram
NBA player analysis
04_ Stack
20_Redis_哨兵模式
How to solve the problem of database content output
【LeetCode】1162-地图分析
03. Preliminary use of golang
面对“缺芯”挑战,飞凌如何为客户产能提供稳定强大的保障?
I made an istio workshop. This is the first introduction
Redux - detailed explanation
10_ Redis_ geospatial_ command
Be a good gatekeeper on the road of anti epidemic -- infrared thermal imaging temperature detection system based on rk3568
14_ Redis_ Optimistic lock
Leetcode skimming -- verifying the preorder serialization of binary tree # 331 # medium
02_线性表_顺序表
LeetCode刷题——去除重复字母#316#Medium