Fibonacci sequence: f(n)=f(n−1)+f(n−2). In order to save memory, f(n-1) and f(n-2) are saved by continuously updating a and b during the calculation process.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution(object): defclimbStairs(self, n): """ :type n: int :rtype: int """ a=1 b=2
# When n is 1 or 2, returns directly if n<=2: return n # Use a and b before the update to save the values of f(n-2) and f(n-1) respectively for i inrange(3,n+1): temp=b # After update, b=a+b, that is, f(n)=f(n-2)+f(n-1) b=a+b a=temp
classSolution(object): defmerge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: None Do not return anything, modify nums1 in-place instead. """ final_list=[] p1,p2=0,0
while p1<m or p2<n: # All elements in nums1 have been added, and only elements in nums2 need to be added if p1==m: final_list.append(nums2[p2]) p2+=1 # All elements in nums2 have been added, and only elements in nums1 need to be added elif p2==n: final_list.append(nums1[p1]) p1+=1 # Add elements with smaller values first elif nums1[p1]<nums2[p2]: final_list.append(nums1[p1]) p1+=1 else: final_list.append(nums2[p2]) p2+=1 nums1[:]=final_list
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right classSolution(object): defisSameTree(self, p, q): """ :type p: Optional[TreeNode] :type q: Optional[TreeNode] :rtype: bool """ if p==Noneand q==None: returnTrue elif p==Noneor q==None: returnFalse elif p.val!=q.val: returnFalse # When executing this step, the current nodes of the two binary trees must be the same, and continue to judge their child nodes return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
for j inrange(0,i+1): # Generate ones at the beginning and end of the current row if j==0or j==i: curr_row.append(1) # Generate numbers in the middle of the current row else: curr_row.append(result[i-1][j]+result[i-1][j-1]) result.append(curr_row) return result
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right classSolution(object): defpostorderTraversal(self, root): """ :type root: Optional[TreeNode] :rtype: List[int] """ node_list=[] stack=[] # When backtracking to the parent node, use prev to determine whether the last visited node is the right subtree prev=None
while root or stack: while root: stack.append(root) root=root.left # The left subtree of the element popped from the stack must have been visited root=stack.pop()
# Whether there is a right subtree, or whether the right subtree has been visited ifnot root.right or root.right==prev: node_list.append(root.val) # Update the access record prev=root root=None # Put the current node on the stack and visit its right subtree first else: stack.append(root) root=root.right
Add a virtual head node so that you can unify the operation when deleting nodes, , and there is no need to do special processing when deleting the head node.
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution(object): defreverseList(self, head): """ :type head: Optional[ListNode] :rtype: Optional[ListNode] """ prev,curr=None,head
while curr!=None: # Save the next node of the current node in advance to avoid losing the next node next=curr.next # Reverse two adjacent nodes curr.next=prev
# Update two pointers prev=curr curr=next return prev
Traverse the array from left to right. After finding the number that is zero, continue to find the first non-zero number behind it and exchange its position with it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution(object): defmoveZeroes(self, nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ for i inrange(len(nums)-1): if nums[i]==0: for j inrange(i+1,len(nums)): # Find the first number that is not 0 and swap it if nums[j]!=0: nums[i]=nums[j] nums[j]=0 break
# Count the number of occurrences of all letters in the string for i in s: hash_count[i]=hash_count.get(i,0)+1 # If the number of occurrences of the letter is even, just add it up, otherwise add (the number of occurrences - 1) for key in hash_count.keys(): if hash_count[key]%2==0: length+=hash_count[key] else: length+=hash_count[key]-1 odd_flag=True # If there is a letter that appears an odd number of times, it should be in the middle of the palindrome if odd_flag: length+=1 return length
classSolution(object): defthirdMax(self, nums): """ :type nums: List[int] :rtype: int """ # Sort the array in descending order nums.sort(reverse=True) count=1
for i inrange(1,len(nums)): if nums[i]!=nums[i-1]: count+=1
if count==3: return nums[i] # If there is no third largest number, return the largest number. return nums[0]
for i,num inenumerate(nums): if num==1: count+=1 else: max_count=max(max_count,count) count=0 # The longest subarray of consecutive ones may appear at the end of the array max_count=max(max_count,count) return max_count
If the corresponding nodes of the two binary trees are empty, the corresponding nodes of the merged binary tree are also empty.
If only one of the corresponding nodes of the two binary trees is empty, the corresponding node of the merged binary tree is the non-empty node.
If the corresponding nodes of both binary trees are not empty, the value of the corresponding node of the merged binary tree is the sum of the values of the corresponding nodes of the two binary trees.
This is the basic framework of binary search, and all other variants are based on this framework.
This algorithm can only find the index of the corresponding number. If there are repeated numbers in the array and you need to find the leftmost or rightmost index of the number, this algorithm is not applicable and some improvements need to be made based on this framework.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution(object): defsearch(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ left_index=0 right_index=len(nums)-1
while (left_index<=right_index): mid=left_index+(right_index-left_index)/2
if (nums[mid]==target): return mid elif nums[mid]>target: right_index=mid-1 elif nums[mid]<target: left_index=mid+1
[1013] Partition Array Into Three Parts With Equal Sum
# If the sum of the array is not divisible by 3, return False if arr_sum%3!=0: returnFalse # After dividing the array into three equal parts, the sum of each part average=arr_sum//3
temp_sum=0 sum_list=[]
for i inrange(len(arr)): temp_sum+=arr[i]
if temp_sum==average: # Record the sum of the first two parts sum_list.append(temp_sum) temp_sum=0
# The remaining numbers in the array are counted in the third part iflen(sum_list)==2and i<len(arr)-1: sum_3=sum(arr[i+1:]) sum_list.append(sum_3)
return sum_list[0]==sum_list[1] and sum_list[1]==sum_list[2] returnFalse