http://ac.jobdu.com/problem.php?pid=1384
-
题目描述:
-
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
-
输入:
-
输入可能包含多个测试样例,对于每个测试案例,
输入的第一行为两个整数m和n(1<=m,n<=1000):代表将要输入的矩阵的行数和列数。
输入的第二行包括一个整数t(1<=t<=1000000):代表要查找的数字。
接下来的m行,每行有n个数,代表题目所给出的m行n列的矩阵(矩阵如题目描述所示,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。
-
输出:
-
对应每个测试案例,
输出”Yes”代表在二维数组中找到了数字t。
输出”No”代表在二维数组中没有找到数字t。
-
样例输入:
-
3 351 2 34 5 67 8 93 312 3 45 6 78 9 103 3122 3 45 6 78 9 10
-
样例输出:
-
YesNoNo
原来用Java写的但不知道为什么TLE。。用C++重写通过,明明是一样的算法。难道说Java的Scanner太慢了?
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class S3 {
public static void main(String[] args) throws FileNotFoundException {
BufferedInputStream in = new BufferedInputStream(new FileInputStream("S3.in"));
System.setIn(in);
Scanner cin = new Scanner(System.in);
int row, col, target;
while (cin.hasNext()) {
row = cin.nextInt();
col = cin.nextInt();
target = cin.nextInt();
int[][] array = new int[row][col];
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
array[i][j] = cin.nextInt();
}
}
// printout(array);
process(array, row, col, target);
}
}
public static void process(int[][] array, int row, int col, int target){
boolean found = false;
int i = 0, j = col-1; // 当前坐标
while(i>=0 && i<row && j>=0 && j<col){
if(array[i][j] == target){
found = true;
break;
}
if(target > array[i][j]){ // 舍弃那一行
i++;
}else if(target < array[i][j]){ // 舍弃那一列
j--;
}
}
if(found){
System.out.println("Yes");
}else{
System.out.println("No");
}
}
public static void printout(int[][] array){
for(int i=0; i<array.length; i++){
for(int j=0; j<array[0].length; j++){
System.out.print(array[i][j] + " ");
}
System.out.println();
}
System.out.println("=========================");
}
}
#include <iostream>
#include <stdio.h>
using namespace std;
void process(int** array, int row, int col, int target){
bool found = false;
int i=0, j=col-1;
while(i>=0 && i<row && j>=0 && j<col){
if(array[i][j] == target){
found = true;
break;
}
if(target > array[i][j]){
i++;
}else if(target < array[i][j]){
j--;
}
}
if(found){
cout << "Yes" << endl;
}else{
cout << "No" << endl;
}
}
int main() {
#ifndef ONLINE_JUDGE
freopen("S3.in", "r", stdin);
freopen("S3.out", "w", stdout);
#endif
int row, col, target;
while (scanf("%d%d%d", &row, &col, &target) != -1) {
int** array = new int*[row];
for(int i=0; i<row; i++){
array[i] = new int[col];
}
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
scanf("%d", &array[i][j]);
}
}
process(array, row, col, target);
}
return 0;
}