Subject description:
https://leetcode-cn.com/problems/search-a-2d-matrix-ii/submissions/
Prepared by an efficient algorithm to search m x n matrix of a target matrix target. This matrix has the following characteristics:
Elements of each row in ascending order from left to right.
Element of each column from top to bottom in ascending order.
Example:
Existing matrix multiplied as follows:
[
[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]
]
given target = 5, returns true.
Given target = 20, returns false.
Topic analysis:
1, first look at the title, I feel this question directly for two cycles to get, why or medium difficulty it? According to violent solution, after the submission they can do, but with a very long time;
2, time-consuming solution causes of violence are: the program takes all of the search space;
3, just look at the recent ideological divide and conquer, divide and conquer description is probably thinking: dividing a complex problem into simpler sub-problems, and then merge into a final solution of the problem child of the solution;
4, the title rows and columns are in ascending order, so head pop out of binary search, binary search method is to use a divide and conquer idea;
5, binary search method: For a ascending linear structure, when searching target, and the target may be first intermediate value compared linear structure, equal to an intermediate value that represents a target value found; if it exceeds the intermediate value, the target line may after half structure;
Less than the intermediate value, the target structure may be half of the line; repeat the previous step, you will eventually get the final result, and the search space occupancy rate of about 50%;
6, when this question using dichotomy, there is an optimal point, since the rows and columns are in ascending order, it is possible to use a smaller width dichotomy rows or columns;
Java code & buckle force operating results --- Violence Act:
public boolean searchMatrix1(int[][] matrix, int target) { if (matrix.length == 0) { return false; } int colSize = matrix[0].length; for (int[] ints : matrix) { for (int j = 0; j < colSize; j++) { if (ints[j] == target) { return true; } } } return false; }
Java code & buckle force operating results --- dichotomy:
public boolean searchMatrix2(int[][] matrix, int target) { if (matrix.length == 0) { return false; } for (int[] ints: matrix) { boolean result = binarySearch(0, ints.length - 1, ints, target); if (result) { return true; } } return false; } private boolean binarySearch(int start, int end, int[] nums, int target) { if (start <= end) { int middle = (start + end) >> 1; if (nums[middle] == target) { return true; } else if (nums[middle] > target) { return binarySearch(start, middle - 1, nums, target); } else { return binarySearch(middle + 1, end, nums, target); } } return false; }
Java code & buckle force operating results --- optimization dichotomy: