当前位置:网站首页>【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]
边栏推荐
- Solution of Queen n problem
- Leetcode skimming -- incremental ternary subsequence 334 medium
- 【LeetCode】344-反转字符串
- 彻底弄懂浏览器强缓存和协商缓存
- 15_Redis_Redis.conf详解
- YOLOV5 代码复现以及搭载服务器运行
- Tidb cross data center deployment topology
- Guangzhou Emergency Management Bureau issued a high temperature and high humidity chemical safety reminder in July
- 党史纪实主题公益数字文创产品正式上线
- 终于搞懂了JS中的事件循环,同步/异步,微任务/宏任务,运行机制(附笔试题)
猜你喜欢

SQL transaction

17_Redis_Redis发布订阅

4. Jctree related knowledge learning

08_ strand

20_ Redis_ Sentinel mode

Redux - detailed explanation

5. Practice: jctree implements the annotation processor at compile time

面对“缺芯”挑战,飞凌如何为客户产能提供稳定强大的保障?

How does the computer set up speakers to play microphone sound

04_ Stack
随机推荐
高考分数线爬取
07_ Hash
自定义异常
2022 college students in Liaoning Province mathematical modeling a, B, C questions (related papers and model program code online disk download)
LeetCode刷题——去除重复字母#316#Medium
【LeetCode】417-太平洋大西洋水流问题
How to choose a third-party software testing organization for automated acceptance testing of mobile applications
Leetcode skimming -- incremental ternary subsequence 334 medium
Guangzhou Emergency Management Bureau issued a high temperature and high humidity chemical safety reminder in July
夏季高考文化成绩一分一段表
FPGA - clock-03-clock management module (CMT) of internal structure of 7 Series FPGA
10_ Redis_ geospatial_ command
PTA 天梯赛习题集 L2-001 城市间紧急救援
6.12 critical moment of Unified Process Platform
20_Redis_哨兵模式
20_ Redis_ Sentinel mode
党史纪实主题公益数字文创产品正式上线
Real estate market trend outlook in 2022
I made an istio workshop. This is the first introduction
【LeetCode】1140-石子游戏II