LeetCode3 Search a 2D Matrix

    xiaoxiao2021-03-25  82

    LeetCode3 Search a 2D Matrix 1、题目描述 Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer of the previous row. For example, Consider the following matrix: [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] Given target = 3, return true. 2,解题思路 首先将特定的二维矩阵转化为按大小排列的一位数组 利用二分法搜索目标值 3、实现代码

    #include<iostream> using namespace std; int main (){ cout<<"please input the size of the m x n matrix"<<endl; int m,n; cin>>m>>n; int mn=m*n; int mat[m][n],mat1[mn]; int k=0; cout<<"please input elements of the matrix: "<<endl; for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ cin>>mat[i][j]; mat1[k]=mat[i][j]; k++; } } cout<<"please input the search number: "; int dest; cin>>dest; int indb=0,inde=mn-1; int b=mat1[indb],e=mat1[inde]; int ind=mn/2,med=mat1[ind]; bool ans=0; if( (b<=dest) && (dest<=e) ){ if((dest==b)||(dest==e)) ans=1; else{ while(inde-indb>1){ if(dest==med){ ans=1; break; } else{ if(dest<med){ e=med; inde=ind; ind=(indb+inde)/2; med=mat1[ind]; } else{ b=med; indb=ind; ind=(indb+inde)/2; med=mat1[ind]; } } } if((dest==b)||(dest==e)){ ans=1; } } } if(ans) cout<<"ture"<<endl; else cout<<"false"<<endl; return 0; }

    4、实验结果

    转载请注明原文地址: https://ju.6miu.com/read-33807.html

    最新回复(0)