Leetcode解题报告:74. Search a 2D Matrix

    xiaoxiao2022-06-24  24

    题目大意:

    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.

    难度:Medium

    解题思路: 由于这道题中,第 i+1 行的所有元素比第i行都大, 我们可以把这个二维数组简化为一个有序的一维数组。 在二维数组中,一个元素的行列坐标记为x,y,每行的元素个数记为n,行的数目记为m,那么在一维数组中,该元素对应的下标就是x*n+y,在一维数组中,元素按照大小已经排好序了,那么我们可以采取二分查找的方式寻找目标值。 取中间位置的元素为pivot,如果目标值就是这个元素,就返回true。如果目标值比pivot小,就用同样的方法搜索下标比pivot下标小的区间,如果比pivot大,就搜索下标大于pivot下标的区间,直到搜索到目标值返回true,或者区间的起始下标大于终点下标就可以认为数组中没有目标值。  

        具体操作中,我们可以从起始下标0,终止下标为数组的行数*数组的列数-1作为终点下标开始按照如上的思想递归地进行搜索,中间位置mid=(start+end)/2, 在二维数组中对应的位置为(mid/n,mid%n)其中n是每行的元素个数。

       这种方法的时间复杂度就是二分查找的时间复杂度,O(logn)

    class Solution { public: bool helper(vector<vector<int>>& nums,int start,int end,int target) { int mid=(start+end)/2; int x=mid/nums[0].size(); int y=mid%nums[0].size(); if(start>end) return false; if(nums[x][y]==target) { return true; } else if(nums[x][y]>target) { return helper(nums,start,mid-1,target); } else return helper(nums,mid+1,end,target); } bool searchMatrix(vector<vector<int>>& matrix, int target) { if(matrix.size()==0) return false; else return helper(matrix,0,matrix[0].size()*matrix.size()-1,target); } };

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

    最新回复(0)