Romance wins the title animation algorithms offer | two-dimensional array lookup

Title Description

(The length of each one-dimensional array of same), each row from left to right in order of ascending sort, to sort each column in a two-dimensional array in order of increasing from top to bottom. A complete function, enter such a two-dimensional array and an integer, it is determined whether the array contains the integer.

analysis

According subject description, the head of our two-dimensional number like this:

Here Insert Picture Description

Careful observation of this array can be found in the lower left of the element (4) has a feature that the elements on the right than it is large, it is small than the above elements. This particular element provides us with a very good search path , we can, if the current element is smaller than the target value, we would walk to the right path by comparing elements continue to find larger elements, otherwise we up walking path.

algorithm

Use of its properties, our algorithm is to start from the bottom-left elements, compare the current element to the target if the current element is less than the target value, we move to the elements on the right to compare again. On the contrary, we move to the top of the elements, and compared again. This process will continue until we find the target, or move up to an array boundary.

Moving map presentation

Here Insert Picture Description

Java code

public class Solution {
    public boolean Find(int target, int [][] array) {
        int rows = array.length;
        int cols = array[0].length;

		// 此为左下角元素的位置
        int i = rows - 1;
        int j = 0;

        while (i >= 0 && j < cols) {
            int value = array[i][j];

            if (target == value) {
                return true;
            }

            if (target < value) {
            	// 如果当前元素大于目标值,向上移动
                i--;
            } else {
            	// 如果当前元素小于目标值,向右移动
                j++;
            }
        }
        return false;
    }
}

Algorithm efficiency analysis

FIG driven can be seen, this algorithm will be negative each time a row or, in the worst case is will traverse the ranks, and therefore the efficiency of the algorithm is:

O (M + N)

Where M is the number of rows, N being the number of columns.

Published 14 original articles · won praise 8 · views 2171

Guess you like

Origin blog.csdn.net/vandavidchou/article/details/104061190