笔试编程

二维数组中的查找

Q: 在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

A1: 遍历整个二维数组,O(n^2)

A2: 从右上或者左下开始查找。从右上开始查找:如果数组中的数比这个整数大,向左移动一位,如果数组中的数比这个数小,向下移动一位,O(n)

# -*- coding:utf-8 -*-
class Solution:
    # array 二维列表 def Find(self, target, array): # write code here num_row = len(array) num_col = len(array[0]) if not array: return False i, j = 0, num_col-1 while i < num_row and j >= 0: if array[i][j] < target: i += 1 elif array[i][j] > target: j -= 1 else: return True return False if __name__ == "__main__": array = [ [1,2,3,4], [2,3,4,5], [3,4,5,6] ] target = 10 sl = Solution() print (sl.Find(target, array)) 

输出:

False

替换空格

Q: 请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

A1: 先计算最终需要给出的长度,然后建立两个指针p1,p2,p1指向原始字符串的末尾,p2指向替换后的字符串的末尾。同时移动p1,p2, 将p1指的内容逐个复制到p2, 当p1遇到空格时,在p2处插入 %20, p1向前移动一个位置,p2向前移动3个位置,当p1和p2位置重合时,全部替换完成。

A2:python中可以利用append() [O(1)],新建list,一次遍历,碰到空格就添加 %20,否则就添加原始字符串s内容。

# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串 def replaceSpace(self, s): # write code here result = '' for char in s: if char == ' ': result += '%20' else: result += char return result if __name__ == "__main__": s = Solution() print (s.replaceSpace('hello lihua')) 

输出:

hello%20lihua

从尾到头打印链表arrayList

遍历链表,保存在list中,然后倒序输出

# -*- coding:utf-8 -*-

class Node:
    def __init__(self,val=None,next = None): self.val = val self.next = next class Solution: # 返回从尾部到头部的列表值序列,例如[1,2,3] def printListFromTailToHead(self, listNode): # write code here if listNode == None: return [] result = [] while listNode != None: result.append(listNode.val) listNode = listNode.next return result[::-1] if __name__ == "__main__": link = Node(1, Node(2, Node(3, Node(4, Node(5, Node(6, Node(7, Node(8, Node(9))))))))) s = Solution() print s.printListFromTailToHead(link) 

输出:

[9, 8, 7, 6, 5, 4, 3, 2, 1] 

重建二叉树

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,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 pre == None or len(pre) == 0: return None root = TreeNode(pre[0]) i = tin.index(root.val) root.left = self.reConstructBinaryTree(pre[1:i + 1], tin[:i]) root.right = self.reConstructBinaryTree(pre[i + 1:], tin[i + 1:]) return root if __name__ == "__main__": s = Solution() root = s.reConstructBinaryTree([1,2,4,7,3,5,6,8], [4,7,2,1,5,3,8,6]) print root 

输出:

<__main__.TreeNode instance at 0x0000000013A6A708>
来源:赚钱

猜你喜欢

转载自www.cnblogs.com/1994jinnan/p/12366906.html