在行列都排好序的矩阵中找指定的数-Java
在行列都排好序的矩阵中找指定的数
http://www.nowcoder.com/questionTerminal/b929be9dbbaa489a91afa3fec195c228
1、按题意来暴力解法
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main{ public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String[] string = reader.readLine().split(" "); int n = Integer.parseInt(string[0]); int m = Integer.parseInt(string[1]); int k = Integer.parseInt(string[2]); for (int i = 0; i < n; i++) { string = reader.readLine().split(" "); for (int j = 0; j < m; j++) { if (Integer.parseInt(string[j]) == k) { System.out.println("Yes"); return; } } } reader.close(); System.out.println("No"); } }
2、优化方法,从右上角开始查找
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main{ public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String[] string = reader.readLine().split(" "); int n = Integer.parseInt(string[0]); int m = Integer.parseInt(string[1]); int k = Integer.parseInt(string[2]); int[][] arr = new int[n][m]; for(int i = 0;i < n;++i){ string = reader.readLine().split(" "); for(int j = 0;j < m;++j){ arr[i][j] = Integer.parseInt(string[j]); } } reader.close(); int x = 0, y = m -1; while( x < n && y >= 0){ if(arr[x][y] == k){ System.out.println("Yes"); return; }else if(arr[x][y] < k){ x++; }else{ y--; } } System.out.println("No"); } }