当前位置:网站首页>【LeetCode】977-有序數組的平方
【LeetCode】977-有序數組的平方
2022-07-02 15:35: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]
边栏推荐
- 20_ Redis_ Sentinel mode
- Application of CDN in game field
- 03. Preliminary use of golang
- Redux——详解
- 4. Jctree related knowledge learning
- Libcurl Lesson 13 static library introduces OpenSSL compilation dependency
- Solve the problem of frequent interruption of mobaxterm remote connection
- 微信支付宝账户体系和支付接口业务流程
- 自定义异常
- Kibana basic operation
猜你喜欢
面对“缺芯”挑战,飞凌如何为客户产能提供稳定强大的保障?
微信支付宝账户体系和支付接口业务流程
LeetCode刷题——奇偶链表#328#Medium
Facing the challenge of "lack of core", how can Feiling provide a stable and strong guarantee for customers' production capacity?
Steps for Navicat to create a new database
语义分割学习笔记(一)
07_ Hash
02_ Linear table_ Sequence table
19_ Redis_ Manually configure the host after downtime
15_Redis_Redis.conf详解
随机推荐
How to find a sense of career direction
Bing. Com website
【LeetCode】1140-石子游戏II
夏季高考文化成绩一分一段表
【Leetcode】167-两数之和II -输入有序数组
JVM architecture, classloader, parental delegation mechanism
Force deduction solution summarizes the lucky numbers in 1380 matrix
How to write sensor data into computer database
10_ Redis_ geospatial_ command
04_ 栈
密码学基础知识
Real estate market trend outlook in 2022
Leetcode skimming -- verifying the preorder serialization of binary tree # 331 # medium
工程师评测 | RK3568开发板上手测试
How to intercept the value of a key from the JSON string returned by wechat?
10_Redis_geospatial_命令
【LeetCode】876-链表的中间结点
How does the computer set up speakers to play microphone sound
Yolov5 code reproduction and server operation
搭载TI AM62x处理器,飞凌FET6254-C核心板首发上市!