明天国庆,每年这个时候学校的三方也差不多下来了,各个企业自然也会催着签合约。
明年这个时候,如何决胜秋招?那会就是我们了该认真考虑了。
前段时间和已经拿到offer
的学长交流,也看了些他们的面经,了解到今年的行情不是太好,除过一些大厂不受影响外,好些企业都有所缩招。互联网曾一度发展相当迅猛,这个势头还会持续,只是互联网行业的红利已经到了瓶颈期了。以后再这个行业捞金只会更难,对求职者的要求也自然会提高。
和找工作的同学交流,殊途同归:找工作要趁早做准备。这不,作为渣硕的我们,现在已经日常刷题了。准备将最近做的题分享出来,这里有我的解题思路。一道题一般会采用好几种方法来尝试,每种方法都有较详细的思路。
本期题目概览
chapter2
试题 3:二维数组中的查找
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,
每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,
判断数组中是否含有该整数。
试题 4:替换空格
请实现一个函数,将一个字符串中的每个空格替换成“ ”。
例如,当字符串为We Are Happy.则经过替换之后的字符串为We Are Happy。
试题 5:从尾到头打印链表
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
试题 6:重建二叉树
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
相关代码
试题 3:二维数组中的查找
# 有序数组;
# 思路:从左下角或者右上角开始比较
# -*- coding:utf-8 -*-
class Solution:
# array 二维列表
def Find(self, target, array):
# write code here
rows, cols = len(array)-1, len(array[0])
row, col = rows, 0
while row >= 0 and col <= cols-1:
if (array[row][col] == target):
return True
elif (array[row][col] > target):
row -= 1
else:
col = 1
return False
试题 4:替换空格
# solutions 1
# 使用python内置函数
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
return s.replace(' ', ' ')
# solution 2
# 正则表达式
import re
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
# ret = re.compile(' ')
# return ret.sub(' ', s)
return re.sub(r'\s', lambda m: ' ', s)
试题 5:从尾到头打印链表
# 这个示例完整的创建一个链表,并且去遍历从尾到头打印出来
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# 在牛客网上线上编程,我们只需书写这一段就行
class Solution:
# 返回从尾部到头部的列表值序列
def printListFromTailToHead(self, listNode):
_stack = []
while listNode:
# 每次将元素插入到列表的头部(第一个元素所在位置)
_stack.insert(0, listNode.val)
listNode = listNode.next
return _stack
if __name__ == '__main__':
pHead = ListNode(1)
p = pHead
for i in range(2, 11):
node = ListNode(i)
p.next = node
p = node
print(Solution().printListFromTailToHead(pHead))
试题 6:重建二叉树
# -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
# write code here
if not pre or not tin:
return None
root = TreeNode(pre[0])
# 查找根节点在中序遍历结果中的位置
pos = tin.index(pre[0])
root.left = self.reConstructBinaryTree(pre[1:1 pos], tin[:pos])
root.right = self.reConstructBinaryTree(pre[pos 1:], tin[pos 1:])
return root
if __name__ == '__main__':
pre = [1, 2, 4, 7, 3, 5, 6, 8]
tin = [4, 7, 2, 1, 5, 3, 8, 6]
print(Solution().reConstructBinaryTree(pre, tin).val)
print(Solution().reConstructBinaryTree(pre, tin).left.val)
本次的四道题目,此外,我将目前做的所有题目均放到了github上,有需要的同学请点击原文阅读,日后将会继续更新剩下的题目。
明天国庆,祝大家玩的开心!
剑指offer-github
谈风月之余谈技术