二维数组中的查找
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>
两个栈实现一个队列
stack2作为中转stack,直接对stack1做push,pop的时候将stack1的pop到stack2中,便可以实现。stack:先入后出,queue:后入先出。
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 len(self.stack1) == 0 and len(self.stack2) == 0:
return None
if len(self.stack2) == 0:
while len(self.stack1) != 0:
self.stack2.append(self.stack1.pop())
return self.stack2.pop()
if __name__ == "__main__":
s = Solution()
s.push(1)
s.push(2)
s.push(3)
print s.pop()
print s.pop()
s.push(5)
print s.pop()
print s.pop()
输出:
1
2
3
5
旋转数组的最小数字
Q: 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
A1: 遍历数组;
A2: 二分查找的变形,旋转数组的首元素肯定不小于旋转数组的尾元素,找一个中间点,如果中间点比首元素大,说明最小数字在中间点后面,如果中间点比尾元素小,说明最小数字在中间点前面。然后循环。 但是在一次循环中,首元素小于尾元素,说明该数组是排序的,首元素就是最小数字,如果出现首元素、尾元素、中间值三者相等,则只能在此区域中顺序查找。
A3: 使用 min(list)
A1: 遍历数组
# -*- coding:utf-8 -*-
class Solution:
def minNumberInRotateArray(self, rotateArray):
# write code here
if not rotateArray:
return None
result = rotateArray[0]
for item in rotateArray:
if item < result:
result = item
return result
if __name__ == "__main__":
s = Solution()
print (s.minNumberInRotateArray([4,5,6,7,8,2,3]))
输出:
2
A2: 二分查找
class Solution:
def minNumberInRotateArray(self, rotateArray):
# write code here
if len(rotateArray) == 0:
return 0
left,right = 0,len(rotateArray)-1
if rotateArray[left] < rotateArray[right]:
return rotateArray[left]
else:
while (right - left) > 1:
middle = (left+right)/2
if rotateArray[middle] <= rotateArray[right]:
right = middle
elif rotateArray[middle] >= rotateArray[left]:
left = middle
return min(rotateArray[left], rotateArray[right])
if __name__ == "__main__":
s = Solution()
print (s.minNumberInRotateArray([4,5,6,7,8,2,3]))
输出:
2
A3: 使用 min(list)
class Solution:
def minNumberInRotateArray(self, rotateArray):
# write code here
return min(rotateArray)
if __name__ == "__main__":
s = Solution()
print (s.minNumberInRotateArray([4,5,6,7,8,2,3]))
输出:
2
来源:oschina
链接:https://my.oschina.net/u/3696975/blog/3175312