第四范式2019-09-09 在线笔试原题
此题是剑指Offer第3题:二维数组中的查找原题,也是LeeCode第74题:Search a 2D Matrix,也同样是第四范式2019-09-09 在线笔试原题:矩阵查数。
代码
此题比剑指Offer和LeetCode题目多了一些条件限制,所以需要考虑时间复杂度和空间复杂度。网上很多版本的代码并不能直接AC。下面的C++代码 AC,而Python 60%通过。
C++
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
bool processMatrix(int target, vector<vector<int> >& matrix) {
if (matrix.empty())return false;
//if (target < matrix[0][0])return false;
int _length = matrix.size();
for (int i = 0; i < _length; i++)
{
if (matrix[i].empty())continue;
else if (target >= matrix[i][0])
{
if (target <= matrix[i][matrix[i].size() - 1])
{
for (int j = matrix[i].size() - 1; j >= 0; j--)
{
if (target == matrix[i][j])return 1;
else if (target > matrix[i][j])break;
}
}
else {
continue;
}
}
else return false;
}
return false;
}
};
int main()
{
// 输入矩阵m,n
int m, n;
cin >> m >> n;
vector<vector<int>> matrix;
matrix.resize(m);
// 输入矩阵
for (int i = 0; i < m; ++i){
matrix[i].resize(n);
for (int j = 0; j < n; ++j)
cin >> matrix[i][j];
}
// 输入待查询数值
int num;
cin >> num;
Solution s;
if (s.processMatrix(num, matrix))
cout << "true";
else
cout << "false";
return 0;
}
Python
# -*- coding:utf-8 -*-
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix or not matrix[0]:
return False
rows = len(matrix)
cols = len(matrix[0])
row, col = 0, cols - 1
while True:
if row < rows and col >= 0:
if matrix[row][col] == target:
return True
elif matrix[row][col] < target:
row += 1
else:
col -= 1
else:
return False
input1 = input().split(" ")
m = int(input1[0])
n = int(input1[1])
array = []
for i in range(m):
temp = []
input2 = input().split(" ")
#print(input2)
for j in input2:
temp.append(int(j))
array.append(temp)
#print(array)
num = int(input())
s = Solution()
if s.searchMatrix(array, num):
print("true")
else:
print("false")
参考
https://www.nowcoder.com/profile/9734827/codeBookDetail?submissionId=12713594