leetcode 378. 有序矩阵中第 K 小的元素 class Solution { #define ll long long public: int cal(int mid,vector<vector<int>>&ma){ int n=ma.size(),i=n-1,j=0,res=0; while(i>=0&&j<n){ if(ma[i][j]<=mid) res+=i+1,++j; else --i; } return res; } int kthSmallest(vector<vector<int>>& ma, int k) { int n=ma.size(),m=min(n-1,(int)sqrt(k)+1); int low=ma[0][0],high=ma[m][m],mid; while(low<=high){ mid=((ll)low+high)>>1; if(cal(mid,ma)>=k) high=mid-1; else low=mid+1; } return high+1; } }; 剑指 Offer 04. 二维数组中的查找 class Solution { public: bool findNumberIn2DArray(vector<vector<int>>& ma, int target) { int n=ma.size(); if(!n) return false; int m=ma[0].size(),i=n-1,j=0; while(i>=0&&j<m){ if(ma[i][j]==target) return true; if(ma[i][j]>target) --i; else ++j; } return false; } };