"Sword Pointing Offer" Java implementation - search in two-dimensional array

Topic description

In a two-dimensional array, 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, and determine whether the array contains the integer.

ideas

This topic is relatively simple. Since each row of the two-dimensional array is incremented, it can be traversed by row first. If the first element is smaller than the target, then the target exists in the row. A try catch part is added here because one of the test points is empty.

solution


 public class Solution {
    public boolean Find(int target, int [][] array) {
      int hang = array.length;
        for (int i = 0; i < hang; i++) {
    //            找到第一个比target小的一行
            try {
                if (array[i][0] <= target) {
    //                System.out.println(i);
                    for (int j = 0; j < array[i].length; j++) {
                        if (array[i][j] == target) {
                            return true;
                        } else if (array[i][j] > target) {
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                return false;
            }
        }
        return false;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325640494&siteId=291194637