タイトル説明:
n * mの2次元配列では、各行は左から右に昇順で並べ替えられ、各列は上から下に昇順で並べ替えられます。効率的な関数を完成させ、そのような2次元配列と整数を入力し、配列に整数が含まれているかどうかを判断してください。
例:
既存のマトリックスは次のとおりです:
[
[
1、4、7、11、15]、
[ 2、5、8、12、19]、[3、6、9、16、22]、
[10、13 、14、17、24]、
[ 18、21、23、26、30 ]
]
ターゲット= 5の場合、trueを返します。
ターゲット= 20の場合、falseを返します。
制限:
0 <= n <= 1000
0 <= m <= 1000
出典:LeetCode(LeetCode)
リンク:https ://leetcode-cn.com/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof
著作権はLeetCodeが所有しています。商用転載の場合は、公認機関にご連絡ください。非商用転載の場合は、出典を明記してください。
問題解決のアイデア:
この質問は思考の質問であり、パターンを見つけることと見なすこともできます。配列はすべての行とすべての列で順序付けられているため、最初の列または最初の行の最大の要素を選択して判断し、次に最初の行の最大の要素を選択して説明します。
上記の質問で説明した例を見てください。target= 5;まず、右上隅にある15を選択してターゲットで判断します。明らかに15は5より大きいので、ここでは15の列が5より大きいことを説明します。 、次に無視できるので、55の2次元配列を54の2次元配列にカットします。
上記の操作を繰り返します。11とターゲットを比較すると、まだ11の大きさであるため、11の列は5より大きくなります。11の列を削除すると、配列は5から3の2次元配列に縮小されます。上記のように、7をターゲットと比較すると、配列は52の2次元配列に縮小されます。次に、4はターゲットよりも小さく、4は5よりも小さいため、4の行は考慮されません(配列が5 x 2の2次元配列に縮小されていることを忘れないでください)。したがって、配列を縮小します。再び42の2次元配列。この操作を再度実行すると、配列に5が見つかったため、trueが返されます。
**注:**ここでの配列の削除は実際には削除ではありませんが、削除部分は考慮されていません。つまり、ターゲットと同じ要素は絶対にないため、時間を無駄にする必要はありません。比べる。
図:
package com.lzw.test1;
/**
* 在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。
* 请完成一个高效的函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
*
* 示例:
*
* 现有矩阵 matrix 如下:
*
* [
* [1, 4, 7, 11, 15],
* [2, 5, 8, 12, 19],
* [3, 6, 9, 16, 22],
* [10, 13, 14, 17, 24],
* [18, 21, 23, 26, 30]
* ]
* 给定 target=5,返回true。
*
* 给定target=20,返回false。
*
* 限制:
*
* 0 <= n <= 1000
*
* 0 <= m <= 1000
*
* @author puppet
* @create 2021-03-19-9:19
*/
public class jianzhi_Offer_04 {
//从右上角开始
public boolean findNumberIn2DArray(int[][] matrix, int target) {
boolean flag = false;
if (matrix != null && matrix.length > 0 && matrix[0].length > 0){
int row = matrix.length - 1;
int col = matrix[0].length - 1;
int n = row;
int m = col;
while (row >=0 && col >=0){
if(matrix[n - row][col] == target){
flag = true;
break;
}
else if(matrix[n - row][col] < target){
row--;
}
else {
col--;
}
}
}
return flag;
}
//从左下角开始
public boolean findNumberIn2DArray1(int[][] matrix, int target) {
boolean flag = false;
if (matrix != null && matrix.length > 0 && matrix[0].length > 0){
int row = matrix.length - 1;
int col = matrix[0].length - 1;
int n = row;
int m = col;
while (row >=0 && col >= 0){
if(matrix[row][m - col] == target){
flag = true;
break;
}
else if(matrix[row][m - col] < target){
col--;
}
else {
row--;
}
}
}
return flag;
}
public static void main(String[] args) {
int[][] matrix = new int[][]{
{
1,4,7,11,15},{
2,5,8,12,19},
{
3, 6, 9, 16, 22},{
10, 13, 14, 17, 24},{
18, 21, 23, 26, 30}};
jianzhi_Offer_04 obj = new jianzhi_Offer_04();
System.out.println(obj.findNumberIn2DArray1(matrix, 5));
}
}