剑指offer刷题
Posted tfknight
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了剑指offer刷题相关的知识,希望对你有一定的参考价值。
题目描述:
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
思路:
这里用了一个数组reverse,但是实际可以用递归
# -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # 返回从尾部到头部的列表值序列,例如[1,2,3] def printListFromTailToHead(self, listNode): l = [] while listNode: l.append(listNode.val) listNode = listNode.next l.reverse() return l
题目描述:
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
思路:
因为是树的结构,一般都是用递归来实现。
用数学归纳法的思想就是,假设最后一步,就是root的左右子树都已经重建好了,那么我只要考虑将root的左右子树安上去即可。
根据前序遍历的性质,第一个元素必然就是root,那么下面的工作就是如何确定root的左右子树的范围。
根据中序遍历的性质,root元素前面都是root的左子树,后面都是root的右子树。那么我们只要找到中序遍历中root的位置,就可以确定好左右子树的范围。
正如上面所说,只需要将确定的左右子树安到root上即可。递归要注意出口,假设最后只有一个元素了,那么就要返回。
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def reConstructBinaryTree(self, pre, tin): # 递归终止条件 if not pre and not tin: return # 树的根结点 root = TreeNode(pre[0]) # 根结点在中序遍历中的位置 i = tin.index(pre[0]) root.left = self.reConstructBinaryTree(pre[1:i+1], tin[:i]) root.right = self.reConstructBinaryTree(pre[i+1:], tin[i+1:]) return root
题目描述
# -*- coding:utf-8 -*- class Solution: def __init__(self): self.stack1=[] self.stack2=[] def push(self, node): # write code here self.stack1.append(node) def pop(self): # return xx if self.stack2==[]: # stack1一旦装了就输出 while self.stack1: self.stack2.append(self.stack1.pop()) # 这里递归回来确保stack1 stack2是空的 return self.stack2.pop() # 递归回来立刻输出 return self.stack2.pop()
题目描述
n<=39
思路:
背
# -*- coding:utf-8 -*- class Solution: def Fibonacci(self, n): # write code here if n == 0: return 0 if n == 1: return 1 if n == 2: return 1 if n >= 3: s = []*n s.append(1) s.append(1) for i in xrange(2,n): s.append(s[i-1]+s[i-2]) return s[n-1]
题目描述
# -*- coding:utf-8 -*- class Solution: def jumpFloor(self,number): # write code here if (number <= 0) : return 0 if (number == 1) : return 1 if (number == 2) : return 2 first = 1 second = 2 third = 0 for i in range(3,number+1): third = first + second first = second second = third return third
题目描述
得出最终结论,在n阶台阶,一次有1、2、...n阶的跳的方式时,总得跳法为:
| 1 ,(n=0 )
f(n) = | 1 ,(n=1 )
# -*- coding:utf-8 -*- import math class Solution: def jumpFloorII(self, number): # write code here if number <= 0: return 0 else: number = number - 1 return math.pow(2,number) # write code here
题目描述
我的思路,按着这个方式可以的,但是上面运行不通过,没搞懂
# -*- coding:utf-8 -*- class Solution: def rectCover(self, number): # write code here if number <1: return 0 elif number <=3: return number else: number = self.rectCover(number-1)+self.rectCover(number-2) return number
别人做法:
# -*- coding:utf-8 -*- class Solution: def rectCover(self, number): # write code here if number < 1: return 0 p = q = r =0 for i in range(1,number+1): if i == 1: p = q = r =1 elif i == 2: q = r = 2 else: r = q + p p = q q = r return r
题目描述
# -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def FindKthToTail(self, head, k): # write code here l=[] while head!=None: l.append(head) head=head.next if k>len(l) or k<1: return return l[-k]
题目描述
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # 返回ListNode def ReverseList(self, pHead): # write code here if pHead is None: return pHead last = None #指向上一个节点 while pHead: # 先用tmp保存pHead的下一个节点的信息, # 保证单链表不会因为失去pHead节点的next而就此断裂 tmp = pHead.next # 保存完next,就可以让pHead的next指向last了 pHead.next = last # 让last,pHead依次向后移动一个节点,继续下一次的指针反转 last = pHead pHead = tmp return last
题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
思路:
就是另外生成一个链表去匹配
# -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # 返回合并后列表 def Merge(self, pHead1, pHead2): # write code here mergeHead = ListNode(90) # 这里是把头指针给了p p = mergeHead while pHead1 and pHead2: if pHead1.val >= pHead2.val: mergeHead.next = pHead2 pHead2 = pHead2.next else: mergeHead.next = pHead1 pHead1 = pHead1.next mergeHead = mergeHead.next # 看看1和2哪个还没走完的 if pHead1: mergeHead.next = pHead1 elif pHead2: mergeHead.next = pHead2 return p.next
题目描述
链接:https://www.nowcoder.com/questionTerminal/6e196c44c7004d15b1610b9afca8bd88 来源:牛客网 public class Solution { public static boolean HasSubtree(TreeNode root1, TreeNode root2) { boolean result = false; //当Tree1和Tree2都不为零的时候,才进行比较。否则直接返回false if (root2 != null && root1 != null) { //如果找到了对应Tree2的根节点的点 if(root1.val == root2.val){ //以这个根节点为为起点判断是否包含Tree2 result = doesTree1HaveTree2(root1,root2); } //如果找不到,那么就再去root的左儿子当作起点,去判断时候包含Tree2 if (!result) { result = HasSubtree(root1.left,root2); } //如果还找不到,那么就再去root的右儿子当作起点,去判断时候包含Tree2 if (!result) { result = HasSubtree(root1.right,root2); } } //返回结果 return result; } public static boolean doesTree1HaveTree2(TreeNode node1, TreeNode node2) { //如果Tree2已经遍历完了都能对应的上,返回true if (node2 == null) { return true; } //如果Tree2还没有遍历完,Tree1却遍历完了。返回false if (node1 == null) { return false; } //如果其中有一个点没有对应上,返回false if (node1.val != node2.val) { return false; } //如果根节点对应的上,那么就分别去子节点里面匹配 return doesTree1HaveTree2(node1.left,node2.left) && doesTree1HaveTree2(node1.right,node2.right); }
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # 返回镜像树的根节点 def Mirror(self, root): # write code here if root!=None: root.left,root.right=root.right,root.left self.Mirror(root.left) self.Mirror(root.right)
题目描述
思路:
用一个栈data保存数据,用另外一个栈min保存依次入栈最小的数
比如,data中依次入栈,
5
,
4
,
3
,
8
,
10
,
11
,
12
,
1
则min依次入栈,
5
,
4
,
3
,no,no, no, no,
1
no代表此次不如栈
每次入栈的时候,如果入栈的元素比min中的栈顶元素小或等于则入栈,否则不如栈。
# -*- coding:utf-8 -*- class Solution: def __init__(self): # 定义两个栈,其中一个是装小点的 self.stack = [] self.min_stack = [] def push(self, node): # write code here self.stack.append(node) if(not self.min_stack or node <= self.min_stack[-1]): self.min_stack.append(node) def pop(self): # write code here if(self.stack[-1] == self.min_stack[-1]): self.min_stack.pop() return self.stack.pop() def top(self): # write code here return self.stack[-1] def min(self): # write code here return self.min_stack[-1]
题目描述
def PrintFromTopToBottom(self, root): if not root: return [] currentStack = [root] res = [] while currentStack: nextStack = [] for i in currentStack: if i.left: nextStack.append(i.left) if i.right: nextStack.append(i.right) res.append(i.val) currentStack = nextStack return res
题目描述
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: #前序 def preorder(self,root,ans=[]): if root!=None: ans.append(root.val) if root.left: self.preorder(root.left,ans) if root.right: self.preorder(root.right,ans) return ans #中序 def inorder(self,root,ans=[]): # if root.left==None and root.right==None: # ans.append(root.val) # return if root.left: self.inorder(root.left,ans) ans.append(root.val) if root.right: self.inorder(root.right,ans) return ans #后序 def postorder(self,root,ans=[]): if root.left: self.postorder(root.left,ans) if root.right: self.postorder(root.right,ans) ans.append(root.val) return ans
题目描述
class Solution: def VerifySquenceOfBST(self, sequence): # write code here if sequence==None or len(sequence)==0: return False length=len(sequence) root=sequence[length-1] # 在二叉搜索 树中 左子树节点小于根节点 for i in range(length): if sequence[i]>root: break # 二叉搜索树中右子树的节点都大于根节点 for j in range(i,length): if sequence[j]<root: return False # 判断左子树是否为二叉树 left=True if i>0: left=self.VerifySquenceOfBST(sequence[0:i]) # 判断 右子树是否为二叉树 right=True if i<length-1: right=self.VerifySquenceOfBST(sequence[i:-1]) return left and right
题目描述
# -*- coding:utf-8 -*- import itertools class Solution: def Permutation(self, ss): # write code here if not ss: return ss result = [] k = itertools.permutations(ss) for i in k: result.append(‘‘.join(i)) result = list(set(result)) # 一定要排序才能过 result.sort() return result
题目描述
# -*- coding:utf-8 -*- class Solution: def GetLeastNumbers_Solution(self, tinput, k): # write code here if tinput is None: return n = len(tinput) if n < k: return [] tinput = sorted(tinput) return tinput[:k]
题目描述
思路:
掌握str.count(i) 可以查找字符串中元素个数
# -*- coding:utf-8 -*- class Solution: def NumberOf1Between1AndN_Solution(self, n): # write code here a = 0 for i in range(0, n+1): if (‘1‘ in str(i)): ind = str(i).count(‘1‘) a+= ind else: pass return a
题目描述
# -*- coding:utf-8 -*- class Solution: def PrintMinNumber(self, numbers): # write code here temp = [str(x) for x in sorted(numbers, cmp=self.f_cmp)] return ‘‘.join(temp) def f_cmp(self,a,b): if str(a)+str(b) < str(b)+str(a): return -1 elif str(a)+str(b) > str(b)+str(a): return 1 else: return 0
题目描述
# -*- coding:utf-8 -*- class Solution(): def FirstNotRepeatingChar(self, s): dict_n = {} simple_list = [] for i in s: if(i not in dict_n): dict_n[i] = 1 else: dict_n[i]+=1 for i in dict_n: if(dict_n[i]==1): simple_list.append(i) start_pos = [] if(len(simple_list)): for j in simple_list: ind = s.index(j) start_pos.append(ind) start_pos.sort() return start_pos[0] else: return -1
题目描述
# -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def FindFirstCommonNode(self, head1, head2): # write code here list1 = [] list2 = [] node1 = head1 node2 = head2 while node1: list1.append(node1.val) node1 = node1.next while node2: if node2.val in list1: return node2 else: node2 = node2.next
题目描述
假如是空节点,则返回0;
否则,原树的深度由左右子树中深度较的深度加1,为原树的深度。
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def TreeDepth(self, pRoot): # write code here if not pRoot: return 0 return max(1 + self.TreeDepth(pRoot.left), 1 + self.TreeDepth(pRoot.right))
题目描述
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def IsBalanced_Solution(self, pRoot): # write code here if not pRoot: return True # 如果两边的树不是一样高,就不是平衡树 a = abs(self.TreeDepth(pRoot.left) - self.TreeDepth(pRoot.right)) if(a>1): return False # 这一步容易漏,要确保递归到每一个子树(左右)都是平衡的 return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right) def TreeDepth(self, pRoot): # 这里是上一题的最大深度,用来求左右子树的最大 if not pRoot: return 0 left_ = 1 + self.TreeDepth(pRoot.left) right_ = 1 + self.TreeDepth(pRoot.right) return max(left_, right_)
题目描述
输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。
输出描述:
对应每个测试案例,输出两个数,小的先输出.
# -*- coding:utf-8 -*- import itertools class Solution: def FindNumbersWithSum(self, array, tsum): if(array.__len__()==0): return array tsum_list =[] dix_ = 0 result = [] for i in itertools.permutations(array,2): if(i[0]+i[1]==tsum): tsum_list.append(i) for i in tsum_list: if(dix_==0): dix_ = i[0] * i[1] result = [min(i[0], i[1]), max(i[0], i[1])] elif(i[0]*i[1]<dix_): dix_ = i[0]*i[1] result = [min(i[0],i[1]),max(i[0],i[1])] return result
题目描述
对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
# -*- coding:utf-8 -*- class Solution: def LeftRotateString(self, s, n): # write code here return s[n:]+s[:n]
题目描述
字符串翻转思路
注意,用reverse,lst[::-1]都可以
# -*- coding:utf-8 -*- class Solution: def ReverseSentence(self, s): # write code here l=s.split(‘ ‘) return ‘ ‘.join(l[::-1])
题目描述
# -*- coding:utf-8 -*- class Solution: def __init__(self): self.a = 0 def Sum_Solution(self, n): if n==0: return self.a else: self.a += n return self.Sum_Solution(n-1)
题目描述
public class Solution { public int Add(int num1,int num2) { while (num2!=0) { int temp = num1^num2; num2 = (num1&num2)<<1; num1 = temp; } return num1; } }
以上是关于剑指offer刷题的主要内容,如果未能解决你的问题,请参考以下文章