題目描述
給定一個有N*M的整形矩陣matrix和一個整數k,matrix的每一行和每一列都是排好序的。實現一個函數,判斷k是否在matrix中。
要求時間複雜度o(M+N)空間複雜度o(1)
例如:
0 1 2 5
2 3 4 7
4 4 4 8
5 7 7 9
如果k爲7則返回true;如果k爲6則返回false
實現思路
定義右上角的元素座標爲(l,r) 因爲該矩陣每一行每一列都有序,所以我們判斷經過
具體解釋如下:
0 1 2 5
2 3 4 7
4 4 4 8
5 7 7 9
當前(l,r)定位到矩陣右上角的5,判斷5和輸入值進行比較 5>4 所以根據有序
判斷2<4 所以2下面這一列可能會有輸入值,我們令l++,依次比較2下面的元素和
繼續上述操作知道超出邊界(l>matrix.length||r<0)
都沒找到返回false
代碼
public class code_03 {
public static void main(String[] args) {
int[][] matrix = {{0, 1, 2, 5}, {2, 3, 4, 7}, {4, 4, 4, 8}, {5, 7, 7, 9}};
System.out.println("不存在" + IsEmerge(matrix, -1));
System.out.println("存在" + IsEmerge(matrix, 5));
}
public static boolean IsEmerge(int[][] matrix, int k) {
int l, r;
//定義右上角的點座標(l,r)
l = 0;
r = matrix[0].length - 1;
while (l < matrix.length && r >= 0) {
if (matrix[l][r] > k) {
r--;
} else if (matrix[l][r] < k) {
l++;
} else if (matrix[l][r] == k) {
return true;
}
}
return false;
}
}