Search a 2D Matrix 搜索一个二维矩阵

  1. #include
    using namespace std;
    int getFirstBigger(int intarr[], int length,int key)
    {
    int left = 0;
    int right = length - 1;
    while (left <= right)
    {
    int mid = (left + right) / 2;
    if (intarr[mid] > key)
    {
    right = mid - 1;
    }
    else
    {
    left = mid + 1;
    }
    }
    return left;
    }
    bool getEquleFirst(int intarr[], int length, int key)
    {
    int left = 0;
    int right = length - 1;
    while (left <= right)
    {
    int mid = (left + right) / 2;
    if (intarr[mid] == key)
    {
    return true;
    }
    if (intarr[mid] > key)
    {
    right = mid - 1;
    }
    else
    {
    left = mid + 1;
    }
    }
    return false;
    }
    int matrix[3][4] =
    {
    {1,3,5,7},
    {10,11,16,20},
    {23,30,34,50},
    };
    bool isInMatrix(int key)
    {
    int left = 0;
    int right = 3 - 1;
    while (left <= right)
    {
    int mid = (left + right) / 2;
    if (matrix[mid][0] == key)
    {
    return true;
    }
    if (matrix[mid][0] > key)
    {
    right = mid - 1;
    }
    else
    {
    left = mid + 1;
    }
    }
    if (left == 0)
    {
    return false;
    }
    return getEquleFirst(matrix[left-1],4,key);
    }
    bool isInMatrixHer(int key)
    {
    int len = 3 * 4;
    int left = 0;
    int right = len - 1;
    while (left <= right)
    {
    int mid = (left + right) / 2;
    if (matrix[mid / 4][mid % 4] == key)
    {
    return true;
    }
    if (matrix[mid / 4][mid % 4] > key)
    {
    right = mid - 1;
    }
    else
    {
    left = mid + 1;
    }
    }
    return false;
    }
    int main()
    {
    int intarr[10] = { 1,5,9,11,15,16,25,26,29,34 };
    cout << getFirstBigger(intarr, 10, 50) << endl;
    cout << isInMatrix(100) << endl;
    cout << isInMatrixHer(50) << endl;
    system(“pause”);
    return 0;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值