九度题目1384:二维数组中的查找

题目链接:http://ac.jobdu.com/problem.php?pid=1384

剑指Offer的解释:http://www.cnblogs.com/zhuyf87/archive/2013/03/01/2938013.html

开始的时候思路卡在如果降低时间复杂度上,我想的选点是选左上角和右下角,但是显然复杂度太高......也考虑过蛇形把矩阵剥皮,还考虑过随机选点,然后每次删除一大块留一个一个小矩阵(这个会挺复杂)

现在想想其实哪怕把各种可能的对矩阵的遍历方式都试一遍差不多也能有正确思路。

正确思路就是选左下或者右上的点,这样每次能删除一列


我用的递归写的:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
 
const int SIZE = 1001;
int n,m;
int t;
int mat[SIZE][SIZE];
 
bool getTar(int rs,int rt, int cs, int ct){
    int nct = ct;
    for(int i=ct;i>=cs;i--){
        if(mat[rs][i]>t)nct--;
        else{
            if(mat[rs][i] == t)return 1;
            else{
                break;
            }
        }
    }
    //nct--;
    int nrs = rs;
    for(int i=rs;i<=rt;i++){
        if(mat[i][nct]<t)nrs++;
        if(mat[i][nct] == t)return 1;
        if(mat[i][nct]>t)break;
    }
    //nrs++;
    if(nrs >rt || nct < cs)return 0;
    return getTar( nrs,  rt,  cs,  nct);
}
 
int main(){
    //freopen("in.txt","r",stdin);
    while(~scanf("%d%d%d",&m,&n,&t)){
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                scanf("%d",&mat[i][j]);
            }
        }
        if(getTar(0,m-1,0,n-1)){
            printf("Yes");
        }else{
            printf("No");
        }
        printf("\n");
    }
    return 0;
}
 
/**************************************************************
    Problem: 1384
    User: Zafedom
    Language: C++
    Result: Accepted
    Time:690 ms
    Memory:5432 kb
****************************************************************/

书上O(n)循环搞之

#include <cstdio>
#include <cstring>
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;

const int SIZE = 1001;
int n,m;
int t;
int mat[SIZE][SIZE];

bool getTar(int rs, int rt, int cs, int ct){
    bool result = false;
    if(rt<rs || ct < cs || mat == NULL)return false;
    int nrs=rs, nct=ct;
    while(nrs <=rt && nct >=cs){
        if(mat[nrs][nct] == t)return true;
        else{
            if(mat[nrs][nct] > t){
                nct--;
            }else{
                nrs++;
            }
        }
    }
    return result;
}

int main(){
    //freopen("in.txt","r",stdin);
    while(~scanf("%d%d%d",&m,&n,&t)){
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                scanf("%d",&mat[i][j]);
            }
        }
        if(getTar(0,m-1,0,n-1)){
            printf("Yes");
        }else{
            printf("No");
        }
        printf("\n");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值