从二维数组中找出对应数的下标

从二维数组中找出对应数的下标,思路如下
遍历整个二维数组,当前数组下标值不是要查询的值的时候,就让col++,然后判断col是否大于等于二维数组的col值,如果是,那么说明需要判断下一行了,也就让col=0,row++。搞定!

public class TwoDimensionalArray {

	public static void main(String[] args) {

		int[][] arr = { { 1, 2, 8, 9 }, { 2, 4, 9, 12 }, { 4, 7, 10, 13 }, { 6, 8, 11, 15 } };

		int num = 11;
		int rows = 4;
		int cols = 4;
		Solution2 solution = new Solution2();
		int[] index = solution.findNum(arr, num, rows, cols);
		System.out.println("row=" + index[0] + "col=" + index[1]);

	}

}

class Solution2 {

	public int[] findNum(int[][] arr, int num, int rows, int cols) {
		int[] index = new int[2];
		int row = 0, col = 0;
		boolean flag = false;

		while (row < rows && col < cols) {

			if (arr[row][col] == num) {
				flag = true;
				break;
			} else {
				col++;
				if (col >= cols) {
					row++;
					col = 0;
				}
			}

		}
		if (flag) {
			index[0] = row;
			index[1] = col;
		} else {
			index[0] = -1;
			index[1] = -1;
		}
	}

}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值