当前位置:网站首页>【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_ Sliding window_ Medium_ 395. Longest substring with at least k repeated characters
- 03_線性錶_鏈錶
- 搭载TI AM62x处理器,飞凌FET6254-C核心板首发上市!
- 【LeetCode】1140-石子游戏II
- Redux - detailed explanation
- Infra11199 database system
- 【LeetCode】577-反转字符串中的单词 III
- 10_Redis_geospatial_命令
- 【LeetCode】1162-地图分析
- How to find a sense of career direction
猜你喜欢

Facing the challenge of "lack of core", how can Feiling provide a stable and strong guarantee for customers' production capacity?

Solution of Queen n problem

自定义异常

Practical debugging skills

15_Redis_Redis.conf详解

搭载TI AM62x处理器,飞凌FET6254-C核心板首发上市!

Tidb data migration tool overview

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

YOLOV5 代码复现以及搭载服务器运行

语义分割学习笔记(一)
随机推荐
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
Storage read-write speed and network measurement based on rz/g2l | ok-g2ld-c development board
XML Configuration File
Bing. Com website
20_ Redis_ Sentinel mode
Data analysis thinking analysis methods and business knowledge - business indicators
做好抗“疫”之路的把关人——基于RK3568的红外热成像体温检测系统
Common English abbreviations for data analysis (I)
03_ Linear table_ Linked list
高考录取分数线爬取
Infra11199 database system
6.12 critical moment of Unified Process Platform
2022 年辽宁省大学生数学建模A、B、C题(相关论文及模型程序代码网盘下载)
Beijing rental data analysis
12_Redis_Bitmap_命令
19_ Redis_ Manually configure the host after downtime
LeetCode刷题——统计各位数字都不同的数字个数#357#Medium
Bing. Site Internet
Leetcode skimming -- count the number of numbers with different numbers 357 medium
YOLOV5 代码复现以及搭载服务器运行