赞
踩
题目:977. 有序数组的平方
代码模板:
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
# 双指针,绝对值最大的在2边
i, j = 0, len(nums)-1
res = [0] * len(nums)
k = j
while k > -1:
if nums[i]**2 < nums[j]**2:
res[k] = nums[j]**2
j -= 1
else:
res[k] = nums[i]**2
i += 1
k -= 1
return res
题目:189. 轮转数组(重点题)
代码模板:
class Solution: def rotate(self, nums: List[int], k: int) -> None: """ Do not return anything, modify nums in-place instead. """ # 法2,使用额外空间 n = len(nums) idx = n - k%n res = [0] * n i = j = 0 while i < n: res[i] = nums[(i+idx) % n] i += 1 while j < n: nums[j] = res[j] j += 1
题目:283. 移动零(思路很清晰)
代码模板:
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
# 同向指针,不同条件判断是否右移
i = j = 0
while j < len(nums):
if nums[j] != 0:
# 左侧换完之后保证都是非0数
nums[i], nums[j] = nums[j], nums[i]
i += 1
j += 1
代码模板:
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
# 首尾双指针,常量空间
i, j = 0, len(numbers)-1
while i < j:
if numbers[i] + numbers[j] == target:
return [i+1, j+1]
elif numbers[i] + numbers[j] > target:
j -= 1
else:
i += 1
return [-1, -1]
代码模板:
class Solution: def reverseWords(self, s: str) -> str: # 将s转变为列表,原地修改 s = list(s) i = j = 0 while j < len(s): while j < len(s) and s[j] != ' ': j += 1 # 反转s[i:j+1]部分 k = j j -= 1 while i < j: s[i], s[j] = s[j], s[i] i += 1 j -= 1 j = k+1 i = k+1 return ''.join(s)
伪原地算法
题目:876. 链表的中间结点
代码模板:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
# 快慢指针
low, fast = head, head
while fast and fast.next:
low = low.next
fast = fast.next.next
return low
代码模板:
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: # 伪头,n在要求范围内 ori = ListNode ori.next = head slow = fast = head while n > 0: fast = fast.next n -= 1 slow = ori while fast: slow = slow.next fast = fast.next slow.next = slow.next.next return ori.next
因为删除当前节点需要其上一个节点,所以添加哑节点
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。