Search in two-dimensional array

Posted by mailtome on Tue, 28 Apr 2020 16:56:30 +0200

Title Description

Given a two-dimensional array, each row is incrementally sorted from left to right, and from top to bottom. Given a number, determine whether the number is in the two-dimensional array.

Consider the following matrix:
[
  [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, return true.
Given target = 20, return false.Copy to clipboardErrorCopied

Solutions to problems

Time complexity O(M + N) and space complexity O(1) are required. Where m is the number of rows and N is the number of columns.

The way to solve the problem is that its number must be below it. Therefore, starting from the upper right corner, you can narrow the search range according to the size relationship between target and the current element. The search range of the current element is all elements in the lower left corner.

Code

Follow the breakpoint. It's very clear

package com.janeroad;

/**
 * Created on 2020/4/27.
 *
 * [@author](https://my.oschina.net/arthor) LJN
 */

//Given a two-dimensional array, each row is incrementally sorted from left to right, and from top to bottom. Given a number, determine whether the number is in the two-dimensional array.

public class test1 {
    public boolean find(int target,int [][]arr){
        if(arr==null||arr.length<=1||arr[0].length<=1)
            return false;
        int j=0,k=arr[0].length-1;
        while (j<arr.length&&k>=0){
            if(target==arr[j][k])
                return true;
            else if(target>arr[j][k])
                j++;
            else
                k--;
        }
        return false;
    }

    public static void main(String[] args) {
        int [][] arr=new int[][]{{1,4,7,11,15},{2,5,8,12,19},{3,6,9,16,12},{10,13,14,17,24},{18,21,23,26,30}};
        test1 test1=new test1();
        System.out.println(test1.find(5,arr));
        System.out.println(test1.find(10,arr));
        System.out.println(test1.find(27,arr));
    }
}

Solutions and pictures: https://cyc2018.github.io/CS-Notes/#/notes/4.%20%E4%BA%8C%E7%BB%B4%E6%95%B0%E7%BB%84%E4%B8%AD%E7%9A%84%E6%9F%A5%E6%89%BE

Topics: github