26、 删除有序数组中的重复项
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
i = 0
j = 1
while(j
在leetcode网站上return i+1相当于list[:i+1]
27. 移除元素
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
i = j =0
while j
88. 合并两个有序数组
第一种方法从头开始,但是要增加一个临时数组来保存点 【小的点在前】
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
first = second = 0
sorted = []
while first
第二种从尾部开始遍历,不用考虑位置替代【大的点在前】
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
first = m-1
second = n-1
tail = m+n-1
while first>=0 or second>=0:
if first == -1:
nums1[tail] = nums2[second]
second -= 1
elif second == -1:
nums1[tail] = nums1[first]
first -= 1
elif nums1[first]
125. 验证回文串
class Solution:
def isPalindrome(self, s: str) -> bool:
#s[left].isalnum()
if not s:
return True
left = 0
right = len(s)-1
while left
a.isalum():判断是否为数字或者字母;a.lower():将所有字母变为小写字母
141. 环形链表
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
if not head or not head.next:
return False
fast = slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if slow==fast:
return True
return False
160. 相交链表
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
node1 = headA
node2 = headB
while node1!=node2:
if node1:
node1 = node1.next
else:
node1 = headB
if node2:
node2 = node2.next
else:
node2 = headA
return node1
假设A链表长度为a,B链表长度为b。若它们有公共点,则公共部分长度为c。
上面代码---node1走的路:a+(b-c),node2走的路:b+(a-c)。所以c大于0时,A.B同时指向第一个公共点,若c等于0时,A.B同时指向空
202. 快乐数
class Solution:
def isHappy(self, n: int) -> bool:
pre = set([]) # 判断是否有循环
def cheng(n):
sum = 0
tmp = str(n)
for i in range(len(str(n))):
sum += int(tmp[i])*int(tmp[i])
return sum
while n!=1:
n = cheng(n)
if n in pre:
return False
else:
pre.add(n)
return True
234. 回文链表
用快慢指针,对后半部分链表进行反转,逐个与前面进行对比
class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
def fanzhuan(head):
pre = None
cur = head
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return pre
fast = slow = new = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
mid = fanzhuan(slow)
while mid:
if new.val!=mid.val:
return False
new = new.next
mid = mid.next
return True
将链表转化为数组,用数组反转判断
class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
pre = head
nums = []
while pre:
nums.append(pre.val)
pre = pre.next
if nums==nums[::-1]:
return True
else:
return False