当前位置:网站首页>【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]
边栏推荐
猜你喜欢

密码学基础知识

Equipped with Ti am62x processor, Feiling fet6254-c core board is launched!

XML Configuration File

Yolo format data set processing (XML to txt)

Leetcode skimming -- count the number of numbers with different numbers 357 medium

Pytoch saves tensor to Mat file

07_ Hash

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

Bing.com網站

03_ Linear table_ Linked list
随机推荐
Application of CDN in game field
I made an istio workshop. This is the first introduction
QML pop-up frame, customizable
03_线性表_链表
密码学基础知识
党史纪实主题公益数字文创产品正式上线
MySQL calculate n-day retention rate
MD5加密
LeetCode刷题——奇偶链表#328#Medium
【网络安全】网络资产收集
03.golang初步使用
【LeetCode】344-反转字符串
How to write sensor data into computer database
The traversal methods of binary tree mainly include: first order traversal, middle order traversal, second order traversal, and hierarchical traversal. First order, middle order, and second order actu
13_ Redis_ affair
Guangzhou Emergency Management Bureau issued a high temperature and high humidity chemical safety reminder in July
Force deduction solution summary 2029 stone game IX
17_ Redis_ Redis publish subscription
vChain: Enabling Verifiable Boolean Range Queries over Blockchain Databases(sigmod‘2019)
Steps for Navicat to create a new database