题目描述
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
解题思路
根据题目信息,可以知道输入和输出信息如下:
- 输入: 二维数组和待查询的整数
- 输出: 待查询整数是否在二维数组(True, False)
已知二维数组是呈规律排列,我们可以先确定一个查询起点,再根据已知的排列规律进行查询。如将二维数组左下角元素作为查询起点,比较左下角元素与待查询数值的大小,如果左下角元素小于待查询数值,则根据排列规则,应该将列数+1。再进行比较,直到左下角元素大于待查询数值,此时即可以将行数-1。继续查询,直到左下角元素等于待查询数值,即可返回True,反之,返回False。
解题步骤
二维数组matrix, 二维数组行数: rows,二维数组列数: cols, 待查询数值num
- 先将二维数组转换成一维数组进行处理
- 定义判断初始值为左下角元素matrix[row][col],其中row=rows-1, col=0
- 将二维数组的左下角元素matrix[row][col](或者右上角元素)值与带查询num进行比较,如果matrix[row][col] > num,则–row;如果matrix[row][col] < num,则++col。
- 重复第3步,直到遍历完所有可以遍历的数组元素。
代码
分治法
C++
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
int matrix_rows = array.size();
int matrix_cols = array[0].size();
int row = matrix_rows-1;
int col = 0;
if(matrix_rows == 0 || matrix_cols == 0)
return false;
while(row >= 0 && col < matrix_cols){
if(target == array[row][col])
return true;
else if(target < array[row][col])
row--;
else
col++;
}
return false;
}
};
Python
# -*- coding:utf-8 -*-
class Solution:
# array 二维列表
def Find(self, target, array):
# write code here
# 计算数组的行列
rows = len(array) # 计算行数
cols = len(array[0]) # 计算列数
if rows<=0 or cols<=0:
return False
row = rows-1
col = 0
while row >=0 and col <cols:
if array[row][col] < target:
col = col+1
elif array[row][col] > target:
row = row-1
else:
return True
return False
C++
bool Find(int* matrix,int rows, int columns, int number)
{
bool Find = false;
if(matrix != NULL && rows > 0 && columns > 0)
{
int rows = 0;
int column = columns - 1;
while(row < rows && column >= 0)
{
if(matrix[row * colums + column] == number)
{
found = true;
break;
}
else if(matrix[row * colums + column] > number)
--cloumn;
else
++row;
}
}
return found;
}
暴力法
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
bool Find(vector<vector<int> > array,int target)
{
int row = 0, col = 0, t = 0;
bool isFound = false;
for(int i = 0; i < array.size( ) ; ++i)
{
for(int j = 0; j < array[i].size( ); ++j)
{
//边输入边验证
if(false == isFound && target == array[i][j])
{
//已经找到后就没必要再找了
isFound = true;
}
}
}
return isFound;
}
};
参考
[1] https://github.com/amusi/coding-note/tree/master/Coding Interviews/03_FindInPartiallySortedMatrix
[2] https://blog.youkuaiyun.com/gatieme/article/details/51100125
[3]《剑指Offer》
[4] https://www.nowcoder.com/practice/abc3fe2ce8e146608e868a70efebf62e?tpId=13&tqId=11154&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
后记
数据结构与算法是编程的基础,是程序员必备的能力。
鉴于自身编程能力有待提高,所以开始刷经典的《剑指Offer》、leetcode和各大名企面试题,顺便以优快云博客的形式做笔记,可能会借鉴很多资料,但是都会注明来源。