继完结了上一个专栏《算法图解》,打算继续刷一下《剑指offer》,以每天一道题的进度来更新文章。
选取的网站:牛客网
选取的程序语言:Python 2.7.3
题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
假设查找7,且数组如下定义:
1
2
8
9
2
4
9
12
4
7
10
13
6
8
11
15
\begin{matrix} 1 & 2 & 8 & 9 \\ 2 & 4 & 9 & 12\\ 4 & 7 & 10 & 13 \\ 6 & 8 & 11 & 15 \\ \end{matrix}
124624788910119121315
针对搜索逻辑有:
- 1.由于数组从左到右,从上到下都是递增,那么左侧和上侧的数不会大于当前位置的数,在此基础上有Step2的搜索策略;
- 2.先从矩阵最右上角开始,9>7那么直接不考虑此行此列,矩阵变成 3 × 3 3\times3 3×3;得到数组 2 4 9 4 7 10 6 8 11 \begin{matrix} 2&4&9\\ 4&7&10\\ 6&8&11\\ \end{matrix} 24647891011,重复操作,最右上角元素 9>7,进行下一行下一列;得到数组 4 7 6 8 \begin{matrix} 4&7 \\ 6&8\\ \end{matrix} 4678,此时7=7。那么就确定了 7 在此数组中。
# -*- coding: utf-8 -*-
# 铺垫一下数组、矩阵
def show_example():
a = [1, 2, 3, 4] # 一个数组
b = [[1, 2, 3, 4],
[5, 6, 7, 8]] # 这里就当表示了一个2维矩阵
print "a is", a
print "b is", b
# 针对矩阵的行数 列数 进行输出有
row_b = len(b) # 矩阵b 的行数
col_b = len(b[0]) # 矩阵b 的列数
print "num of row_b is", row_b
print "num of col_b is", col_b
# 这里要学一下 b[0] b[1] 索引是从0开始的
print "1st row of b is", b[0] # [1, 2, 3, 4]
print "2nd row of b is", b[1] # [5, 6, 7, 8]
print "val of element b(1,2) is", b[0][1] # 表示矩阵b的(x,y)元素,b[0][1]表示第一行 第二列所在元素值 理论值为2
show_example()
# -*- coding:utf-8 -*-
class Solution:
# array 二维列表
def Find(self, target, array):
# write code here
rows = len(array)
cols = len(array[0])
if rows > 0 and cols > 0:
row = 0
col = cols - 1
while row < rows and col >= 0:
if target == array[row][col]: # 这里的判断“相等”关系的时候用“==”
return True
elif target < array[row][col]: # 这里观察矩阵,目标值小于当前元素,那么说明在左侧/下侧 row加 col减
col -= 1
else:
row += 1
return False
Reference
附本人Github地址:https://github.com/shiqi0404/NowCoder
包含.md和对应.py文件。欢迎大家下载运行。