当前位置:网站首页>Leetcode 977. Square of ordered array
Leetcode 977. Square of ordered array
2022-07-29 06:22:00 【Zhangchuming ZCM】
Power button | 977. The square of an ordered array
Title screenshot

Method 1 : Direct sort
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
return sorted(num * num for num in nums)All codes for testing
from typing import List
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
return sorted(num * num for num in nums)
class main:
a = Solution()
nums = [-5,-3,-2,-1]
b = a.sortedSquares(nums)
print(b)
if __name__ == '__main__':
main()sorted() function
Python sorted() function | Novice tutorial
Method 2 : Double pointer
The title is Non decreasing sort , The order may change after the square just depends on whether the original array element is zero .
Use the following code to record the subscript of the negative number .
for i in range(0, n):
if nums[i]<0:
flag = i
else:
breakYou can also use enumerate() function
Python enumerate() function | Novice tutorial
for i, num in enumerate(nums):
if num < 0:
flag = i
else:
breakexpand : Realize it by yourself enumerate() function
def my_enumerate(obj):
for i in range(len(obj)):
yield i,obj[i]Set the left and right pointers respectively left=flag,right=flag+1, The left pointer points to the first negative number , Move to the left . The right pointer points to the first nonnegative number , To the right .
Set the loop , As long as the left and right pointers do not reach the leftmost and rightmost , It's been circulating .
Give priority to two extreme situations , namely , Make the pointer on the far left , But the right pointer did not reach the far right ; And the right pointer is on the far right , But the left pointer did not reach the leftmost .
1. When the left pointer is at the leftmost , Always add the element pointed to by the right pointer , And constantly move the right pointer to the right .
2. Reverse the same 2 The reason is .
3. When the left pointer points to an element less than or equal to the right pointer points to an element : Add the element on the left , And move the left pointer to the left .
4. Reverse the same 3 The reason is .
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
n = len(nums)
flag = 0
for i in range(0, n):
if nums[i]<0:
flag = i
else:
break
left, right = flag, flag+1
ans = []
while left >= 0 or right < n:
if left < 0:
ans.append(nums[right] * nums[right])
right += 1
elif right == n:
ans.append(nums[left] * nums[left])
left -= 1
elif (nums[left]*nums[left]) <= (nums[right] * nums[right]):
ans.append(nums[left] * nums[left])
left -= 1
else:
ans.append(nums[right] * nums[right])
right += 1
return ansMethod 3 : Double pointer
Put the two pointers on the left and right sides at the beginning , Compare the size of the square of the element pointed to by the pointer and discharge it into the array , Let them move towards the middle .
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
n = len(nums)
left, right, pos= 0, n-1, n-1
ans = [0]* n
while left <= right :
if nums[left] * nums[left] > nums[right] * nums[right]:
ans[pos] = (nums[left] * nums[left])
left += 1
else:
ans[pos] = (nums[right] * nums[right])
right -=1
pos -= 1
return ans边栏推荐
- Ml self study notes 5
- Dynamic planning summary
- JUC collection class is unsafe
- 动态加载数据
- 【软件工程之美 - 专栏笔记】20 | 如何应对让人头疼的需求变更问题?
- 【软件工程之美 - 专栏笔记】29 | 自动化测试:如何把Bug杀死在摇篮里?
- Pit avoidance: about the interconnection of two hc-05 master-slave integrated Bluetooth modules, there is no connection problem
- FPGA based: moving target detection (schematic + source code + hardware selection, available)
- 进程与进程的概念
- Linked list -------------------------- tail insertion method
猜你喜欢

JUC concurrent knowledge points

LeetCode #14. 最长公共前缀

Based on STM32: couple interactive doll (design scheme + source code +3d drawing +ad circuit)

传统模型预测控制轨迹跟踪——圆形轨迹(功能包已经更新)

Based on stc51: schematic diagram and source code of four axis flight control open source project (entry-level DIY)

FPGA based: moving target detection (supplementary simulation results, available)

顺序表和链表

EPS32+Platform+Arduino 跑马灯

LeetCode #557.反转字符串中的单词 III

ML7 self study notes
随机推荐
Huawei cloud 14 day Hongmeng device development -day7wifi function development
Leetcode 13. Roman numeral to integer
Mathematical modeling experience
传统模型预测控制轨迹跟踪——波浪形轨迹(功能包已经更新)
动态加载数据
FPGA based: multi-target motion detection (hand-in-hand teaching ①)
[beauty of software engineering - column notes] 17 | what is the need analysis? How to analyze?
STM32 MDK(Keil5) Contents mismatch错误总结
Power electronics: single inverter design (matlab program +ad schematic diagram)
From entry to soul: how to use tb6600 single chip microcomputer to control stepping motor with high precision (42/57)
爬取表情包
Huawei cloud 14 day Hongmeng device development -day3 kernel development
爬虫Requests库的一些简单用法
Rowkey设计
crawl笔记
Computer network interview questions
顺序表和链表
synchronized八锁现象理解
【软件工程之美 - 专栏笔记】21 | 架构设计:普通程序员也能实现复杂系统?
Redshift还原SP效果 - SP贴图导出设置及贴图导入配置