1. 程式人生 > >9.6-二維陣列搜尋

9.6-二維陣列搜尋

Given a matrix in which each row and each column is sorted, write a method to find an element in it.

其實很簡單,關鍵在於搜尋的起始點要在矩陣的右上角。

這樣做的好處是方便查詢。如果比目標x小,那麼row++;如果比x大,則col--;

#include <iostream>

using namespace std;
int* search_matrix(int matrix[][4], int n, int m, int x)
{
    int i=0,j=m-1;
    int *ans = new int[2];
    while(i<n && m>=0)
    {
        if(matrix[i][j]==x)
        {
            ans[0]=i;
            ans[1]=j;
            return ans;
        }
        else if(matrix[i][j] < x)
            i++;
        else
            j--;
    }
    return ans;
}
int main()
{
    int matrix[4][4]=
    {
        1,2,3,4,
        5,6,7,8,
        9,10,11,12,
        13,14,15,16
    };
    int *ans = new int[2];
    ans=search_matrix(matrix, 4, 4, 8);
    cout <<"X: " <<ans[0] <<" , Y: " <<ans[1]<<endl;
    free(ans);
    return 0;
}