当前位置:网站首页>【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]
边栏推荐
- 【LeetCode】577-反转字符串中的单词 III
- Leetcode skimming -- verifying the preorder serialization of binary tree # 331 # medium
- 04.进入云原生后的企业级应用构建的一些思考
- Oracle primary key auto increment
- 6.12 企业内部upp平台(Unified Process Platform)的关键一刻
- Solve the problem of frequent interruption of mobaxterm remote connection
- Practical debugging skills
- Be a good gatekeeper on the road of anti epidemic -- infrared thermal imaging temperature detection system based on rk3568
- List set & UML diagram
- 21_ Redis_ Analysis of redis cache penetration and avalanche
猜你喜欢
损失函数与正负样本分配:YOLO系列
04_ 栈
2022 college students in Liaoning Province mathematical modeling a, B, C questions (related papers and model program code online disk download)
Engineer evaluation | rk3568 development board hands-on test
10_ Redis_ geospatial_ command
04_ Stack
20_Redis_哨兵模式
【网络安全】网络资产收集
Application and practice of Jenkins pipeline
16_Redis_Redis持久化
随机推荐
Semantic segmentation learning notes (1)
FPGA - 7系列 FPGA内部结构之Clocking -03- 时钟管理模块(CMT)
Application of CDN in game field
Bing. Site Internet
How to conduct TPC-C test on tidb
11_Redis_Hyperloglog_命令
04.进入云原生后的企业级应用构建的一些思考
List set & UML diagram
Bing.com网站
vChain: Enabling Verifiable Boolean Range Queries over Blockchain Databases(sigmod‘2019)
How to avoid 7 common problems in mobile and network availability testing
Deploy tidb cluster with tiup
【LeetCode】486-预测赢家
Huffman tree: (1) input each character and its weight (2) construct Huffman tree (3) carry out Huffman coding (4) find hc[i], and get the Huffman coding of each character
14_Redis_乐观锁
How to intercept the value of a key from the JSON string returned by wechat?
21_ Redis_ Analysis of redis cache penetration and avalanche
Bing.com網站
5. Practice: jctree implements the annotation processor at compile time
Let your HMI have more advantages. Fet-g2ld-c core board is a good choice