面试题3:数组中重复的数字
题目描述:在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
详细代码:
class Solution:
# 这里要特别注意~找到任意重复的一个值并赋值到duplication[0]
# 函数返回True/False
def duplicate(self, numbers, duplication):
# write code here
length = len(numbers)
for i in range(length):
while numbers[i] != i:
m = numbers[i]
if numbers[m] != m:
numbers[i] = numbers[m]
numbers[m] = m
else:
duplication[0] = m
bresk
break
if duplication[0] == -1: #系统内部设定了duplication[0] = -1
return False
else:
return True
面试题4:二维数组中的查找
题目描述:在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
详细代码:
class Solution:
# array 二维列表
def Find(self, target, array):
# write code here
if array==[]: #注意特殊情况
return False
h = len(array)
w = len(array[0])
i = 0
j = w-1
while i < h and j >= 0: #注意边界能否取到
if array[i][j] == target:
return True
elif array[i][j] > target:
j -= 1
else:
i += 1
return False