判断二维数组中是否存在某值

题目描述:
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

思路:
从数组的左下角元素开始比较,若目标整数等于该元素,则返回true, 若目标整数大于该元素,则 x 右移。若目标整数小于该元素,则 y 上移,重复此操作。

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;
	}
}

注意:

  1. 空二维数组的列长是 1
    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_40307206/article/details/100906613
今日推荐