程序员代码面试指南刷题--第八章.在行列都排好序的矩阵中找指定的数

题目描述

给定一个N×M的整形矩阵matrix和一个整数K, matrix的每一行和每一列都是排好序的。
实现一个函数,判断K是否在matrix中
[要求]
时间复杂度为O(N+M),额外空间复杂度为O(1)。

输入描述:

第一行有三个整数N, M, K
接下来N行,每行M个整数为输入的矩阵

输出描述:

若K存在于矩阵中输出"Yes",否则输出"No"

示例1
输入
2 4 5
1 2 3 4
2 4 5 6

输出
Yes

示例2
输入
2 4 233
1 2 3 4
2 4 5 6

输出
No
import java.util.*;
import java.io.*;
public class Main{
    public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    public static int[][] create(int col,int row)throws IOException{
        int[][] a = new int[col][row];
        for(int i=0;i<col;i++){
            String[] ss = br.readLine().trim().split(" ");
            for(int j=0;j<row;j++){
                a[i][j] = Integer.parseInt(ss[j]);
            }
        }
        return a;
    }
    public static boolean contains(int[][] a,int key) throws IOException{
        int row = a.length;
        int col = a[0].length;
        int i = 0;
        int j = col-1;
        while(i<row&&j>=0){
            if(a[i][j]==key) return true;
            else if(a[i][j]>key) j--;
            else i++;
        }
        return false;
    }
    public static void main(String[] args) throws IOException{
        String[] ss1 = br.readLine().trim().split(" ");
        int row = Integer.parseInt(ss1[0]);
        int col = Integer.parseInt(ss1[1]);
        int key = Integer.parseInt(ss1[2]);
        int[][] matrix = create(row,col);
        boolean result = contains(matrix,key);
        if(result==true){
            System.out.println("Yes");
        }else{
              System.out.println("No");
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值