Determine whether a value exists in a two-dimensional array

Problem 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, and determine whether the array contains the integer.

Idea:
Start comparing from the lower left element of the array. If the target integer is equal to this element, return true. If the target integer is greater than this element, move x to the right. If the target integer is less than the element, y is moved up and the operation is repeated.

public class Solution {
    
    
    public boolean Find(int target, int [][] array) {
    
    
        int lenY = array.length;
		int lenX = array[0].length;
		boolean result = false;
		if (array.length == 1) {
    
    
			return result;
		} else {
    
    
			int x = 0;
			int y = lenY - 1;
			for (int i = 0; i < lenY + lenX; i++) {
    
    
				if (target == array[y][x]) {
    
    
					result = true;
					break;
				} else if (target > array[y][x] && x < lenX - 1) {
    
    
					x += 1;
				} else if (target < array[y][x] && y > 0) {
    
    
					y -= 1;
				}
			}
		}
		return result;
	}
}

Notice:

  1. The column length of an empty two-dimensional array is 1
    Insert image description here

Guess you like

Origin blog.csdn.net/weixin_40307206/article/details/100906613