您的位置:首页 > 其它

Search a 2D Matrix | & II

2016-07-06 10:43 405 查看

Search a 2D Matrix II

Write an efficient algorithm that searches for a value in an m x n matrix, return the occurrence of it.

This matrix has the following properties:

Integers in each row are sorted from left to right.

Integers in each column are sorted from up to bottom.

No duplicate integers in each row or column.

Example

Consider the following matrix:

[
[1, 3, 5, 7],
[2, 4, 7, 8],
[3, 5, 9, 10]
]

Given target =
3
, return
2
.

分析:

因为数组里的数有上面三个特性,所以我们可以从左下角开始找。如果当前值比target大,明显往上走,比target小,往右走,如果一样斜上走。Time complexity: (O(m + n)) (m = matrix.length, n = matrix[0].length)

public class Solution {
/**
* @param matrix: A list of lists of integers
* @param: A number you want to search in the matrix
* @return: An integer indicate the occurrence of target in the given matrix
*/
public int searchMatrix(int[][] matrix, int target) {
// check corner case
if (matrix == null || matrix.length == 0) {
return 0;
}
if (matrix[0] == null || matrix[0].length == 0) {
return 0;
}

// from bottom left to top right
int x = matrix.length - 1;
int y = 0;
int count = 0;

while (x >= 0 && y < matrix[0].length) {
if (matrix[x][y] < target) {
y++;
} else if (matrix[x][y] > target) {
x--;
} else {
count++;
x--;
y++;
}
}
return count;

}
}


Search a 2D Matrix I

Write an efficient algorithm that searches for a value in an mx n matrix.

This matrix has the following properties:

Integers in each row are sorted from left to right.

The first integer of each row is greater than the last integer of the previous row.

Example

Consider the following matrix:

[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]

Given
target = 3
, return
true
.

分析:

根据数组的特点,我们需要找出一个大范围(row),然后再确定小范围。

public class Solution {
/**
* @param matrix, a list of lists of integers
* @param target, an integer
* @return a boolean, indicate whether matrix contains target
*/
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return false;
int rowCount = matrix.length;
int colCount = matrix[0].length;
if (matrix[0][0] > target || matrix[rowCount - 1][colCount - 1] < target) return false;

int row = getRowNumber(matrix, target);

int start = 0;
int end = colCount - 1;

while (start <= end) {
int mid = start + (end - start) / 2;
if (matrix[row][mid] == target) {
return true;
} else if (matrix[row][mid] > target) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return false;

}
//这个方法跟找插入点的那个题一模一样
public int getRowNumber(int[][] matrix, int target) {
int start = 0;
int end = matrix.length - 1;
int width = matrix[0].length;

while (start <= end) {
int mid = start + (end - start) / 2;
if (matrix[mid][width - 1] == target) {
return mid;
} else if (matrix[mid][width - 1] > target) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return start;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: