当前位置:网站首页>[leetcode] 977 square of ordered array
[leetcode] 977 square of ordered array
2022-07-02 15:36:00 【Crisp ~】
Here's a button Non decreasing order Sorted array of integers nums, return The square of each number A new array of , According to the requirements Non decreasing order Sort .
Example 1:
Input : nums = [-4,-1,0,3,10]
Output : [0,1,9,16,100]
explain : After square , The array becomes [16,1,0,9,100]
After ordering , The array becomes [0,1,9,16,100]
Example 2:
Input : nums = [-7,-3,2,3,11]
Output : [4,9,9,49,121]
Tips :
- 1 <= nums.length <= 104
- -104 <= nums[i] <= 104
- nums Pressed Non decreasing order Sort
Advanced :
Please design with a time complexity of O(n) The algorithm solves this problem
# Direct sort
class Solution(object):
def sortedSquares(self, nums):
return sorted(num*num for num in nums)
# Time complexity :O(n \log n)O(nlogn)
# Spatial complexity :O(\log n)O(logn)
# Double pointer
# Because the array sequence is in ascending order , Square is a positive number , So start at both ends , Numbers with large absolute values enter the sequence squared first
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]
边栏推荐
猜你喜欢

06_ Stack and queue conversion

14_Redis_乐观锁

10_ Redis_ geospatial_ command

04_ Stack

Solve the problem of frequent interruption of mobaxterm remote connection

FPGA - clock-03-clock management module (CMT) of internal structure of 7 Series FPGA

Storage read-write speed and network measurement based on rz/g2l | ok-g2ld-c development board

04_ 栈

自定义异常

Redux - detailed explanation
随机推荐
How to choose a third-party software testing organization for automated acceptance testing of mobile applications
10_Redis_geospatial_命令
【Leetcode】167-两数之和II -输入有序数组
【LeetCode】344-反转字符串
【LeetCode】1254-统计封闭岛屿的数量
Mavn builds nexus private server
13_ Redis_ affair
Custom exception
4. Data splitting of Flink real-time project
17_ Redis_ Redis publish subscription
6.12 企业内部upp平台(Unified Process Platform)的关键一刻
Deploy tidb cluster with tiup
18_Redis_Redis主从复制&&集群搭建
17_Redis_Redis发布订阅
03.golang初步使用
【网络安全】网络资产收集
LeetCode_ Sliding window_ Medium_ 395. Longest substring with at least k repeated characters
06_ Stack and queue conversion
How to solve the problem of database content output
提前批院校名称