Jianzhi offer 03: search in a two-dimensional array

❝
永远要这样写代码,好像最终维护你代码的人是个狂暴的、知道你住在哪里的精神病患者—— 小浩算法

❞

Lookup in a two-dimensional array


Title description

In a two-dimensional array (each one-dimensional array has the same length), each row is sorted in increasing order from left to right, and each column is sorted in increasing order from top to bottom. Please complete a function, input such a two-dimensional array and an integer to determine whether the array contains the integer.

solution

Search from the top right of the two-dimensional array:

  • If the element value is equal to target, return true;
  • If the element value is greater than target, cut off this column, namely --j;
  • If the element value is less than target, cut off this line, that is, ++i.
    You can also search from the bottom left of the two-dimensional array. The following code uses the bottom left as the starting point for the search.

Note that you cannot select the numbers at the top left or bottom right, because this will not narrow the search range.

public class Solution {
    /**
     * 二维数组中的查找
     * @param target 目标值
     * @param array 二维数组
     * @return boolean
     */
    public boolean find(int target, int[][] array) {
        if (array == null) {
            return false;
        }
        int rows = array.length;
        int columns = array[0].length;

        int i = rows - 1;
        int j = 0;
        while (i >= 0 && j < columns) {
            if (array[i][j] == target) {
                return true;
            }
            if (array[i][j] < target) {
                ++j;
            } else {
                --i;
            }
        }
        return false;
    }
}

Test case

  1. The two-dimensional array contains the searched numbers (the searched numbers are the maximum and minimum values ​​in the array; the searched numbers are between the maximum and minimum values ​​in the array);
  2. There is no searched number in the two-dimensional array (the searched number is greater/less than the maximum value in the array; the searched number is between the maximum and minimum values ​​of the array but there is no such number in the array);
  3. Special input test (input null pointer).

I organized all the solutions I wrote into an e-book on github, and hit the top of the github rankings in three days! Nearly 5w people downloaded and read! If you want to get it, just go to the link below (remember to give me a star ):

https://github.com/geekxh/hello-algorithm

Guess you like

Origin blog.51cto.com/15076236/2609652