二维数组中的查找

题目描述:

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

题目解答:

第一种:直接使用暴力求解,即二重循环

第二种:从左下角元素往上查找,右边元素是比这个元素大,上边是的元素比这个元素小。于是,target 比这个元素小就往上找,比这个元素大就往右找。如果出了边界,则说明二维数组中不存在 target 元素。

import java.util.*;
import java.math.*;
public class Solution {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		while (input.hasNext()) {
			int m = input.nextInt();
			int n = input.nextInt();
			int[][] a = new int[m][n];
			for (int i = 0; i < m; i++) {
				for (int j = 0; j < n; j++) {
					a[i][j] = input.nextInt();
				}
			}
			while (input.hasNext()) {
				int target = input.nextInt();
				System.out.println("Solution1:");
				System.out.println(Find1(target, a));
				System.out.println("Solution2:");
				System.out.println(Find2(target, a));
			}
		}
		input.close();
	}
	//暴力求解
	private static boolean Find1(int target, int[][] array) {
		int rows = array.length;
		int cols = array[0].length;
		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < cols; j++) {
				if (array[i][j] > target) {
					break;
				}
				if (array[i][j] == target) {
					return true;
				}
			}
		}
		return false;
	}
	//从左下角开始查找,线性求解
	private static boolean Find2(int target, int[][] array) {
		int rows = array.length;
		int cols = array[0].length;
		int i = rows - 1, j = 0;
		while (i >= 0 && j < cols) {
			if (target == array[i][j]) {
				return true;
			} else if (target < array[i][j]) {
				i--;
			} else {
				j++;
			}
		}
		return false;
	}
}

运行结果:

Input:

2 4
1 2 3 6
3 4 5 7
5
0

Output:

Solution1:
true
Solution2:
true
Solution1:
false
Solution2:
false

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值