十六:在行列都排好序的矩陣中找指定數

題目

給定一個元素爲非負整數的二維數組matrix, 每行和每列都是從小到大有序的。
再給定一個非負整數aim, 請判斷aim是否在matrix中。

實現

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;

public class Main {
	
	public static boolean find(int[][] m, int k) {
		int row = 0;
		int col = m[0].length - 1;
		while (row != m.length && col != -1) {
			if (m[row][col] > k) {
				col--;
			} else if (m[row][col] < k) {
				row++;
			} else {
				return true;
			}
		}
		return false;
	}
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		while (in.hasNext()) {
			int n = in.nextInt();
			int m = in.nextInt();
			int[][] matrix = new int[n][m];
			int k = in.nextInt();
			for (int i = 0; i < n; i++) {
				for (int j = 0; j < m; j++) {
					matrix[i][j] = in.nextInt();
				}
			}
			System.out.println(find(matrix, k) ? "Yes" : "No");
			break;
		}
		in.close();
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章