Offer a prove safety: 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.

 

My problem-solving ideas: because each row from left to right in order of ascending sort, so I use a binary search solutions

package com.jianzhioffer;

public class FindArray {
	public static void main(String[] args){
		
		int [][] array = {{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
		
		System.out.println(Find(7, array));
		
	}
	
	 public static boolean Find(int target, int [][] array) {
		int l = array.length;
		int r = array[0].length;
		int i=0;
		for(i=0;i<l;i++){
			int lf = 0;
			int rg = r -1;
			while(lf<=rg){
				int m = (lf + rg)/2;
				if(array[i][m] == target){
					return true;
				}
				if(array[i][m] > target){
					rg = m-1;
				}else{
					lf = m+1;
				}
			}	
		}
		return false;
	 }
}

Someone else's ideas:

Two-dimensional array is ordered, the point of view from the top right corner, to the left of diminishing numbers, numbers down incrementally.
Therefore, from the top right corner to start looking,

  • When you are looking for a large digital numbers than the upper-right corner, down;
  • When looking for a figure than the upper right corner of the digital hours, left;
  • If the boundary, then the two-dimensional array of integers that does not exist.
public class Solution {
    public boolean Find(int target, int [][] array) {
        if(array.length==0 || array[0].length==0)
            return false;
        int m = array[0].length-1;
        int n = 0;
        int temp = array[n][m];
        while(target != temp){
            if(m>0 && n<array.length-1){
                if(target>temp){
                    n = n + 1;
                }else if(target<temp){
                    m = m - 1;
                }
                temp = array[n][m];
            }else{
                return false;
            }
        }
        return true;
    }
}

 

  

Guess you like

Origin blog.csdn.net/m0_37564426/article/details/91436326