LeetCode-240 Search a 2D Matrix II
生活随笔
收集整理的這篇文章主要介紹了
LeetCode-240 Search a 2D Matrix II
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述
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 in ascending from left to right.
- Integers in each column are sorted in ascending from top to bottom.
?
題目大意
給定一個二維整數數組,數組中的行和列都是按照遞增順序排列,要求查找二維數組中是否存在一個給定的數字。
?
示例
E1
Consider the following matrix:
[[1, 4, 7, 11, 15],[2, 5, 8, 12, 19],[3, 6, 9, 16, 22],[10, 13, 14, 17, 24],[18, 21, 23, 26, 30] ]Given?target?= 5, return true.
Given?target?= 20, return false.
?
解題思路
對每行進行二分搜索,若在當前沒有找到給定的數字,則將搜索范圍的終止位置縮小為當前位置(因為當在當前行,搜索停止且未找到數字時,說明找到的位置一定大于或小于目標數字,若小于目標數字,則將位置加一,將二分搜索的終止位置重新賦值更新,因為每一行也是遞增排列,因此在該位置之后的每一行的數字一定大于目標數字。經過該操作可以減少查詢次數)。
?
復雜度分析
時間復雜度:O(log(N))
空間復雜度:O(1)
?
代碼
class Solution { public:bool searchMatrix(vector<vector<int>>& matrix, int target) {if(matrix.size() == 0 || matrix[0].size() == 0)return false;bottom = 0, top = matrix[0].size() - 1;for(int i = 0; i < matrix.size(); ++i) {// 對每一行進行二分查找bool f = binSearch(matrix[i], bottom, top, target);if(f)return true;}return false;}bool binSearch(vector<int>& arr, int sta, int end, int& target) {// 如果二分查找到最后,判斷是否找到目標數字,并且將二分范圍縮小if(sta >= end) {top = (end == arr.size() - 1 ? top : (arr[end] > target ? end : end + 1));return arr[end] == target;}else {int mid = (sta + end) / 2;bool f;// 若找到直接返回trueif(arr[mid] == target) {return true;}// 否則,若中間位置小于目標數字,則返回后半部分位置else if(arr[mid] < target) {f = binSearch(arr, mid + 1, end, target);return f;}// 否則,若中間位置大于目標數字,則返回前半部分位置else {f = binSearch(arr, sta, mid, target);return f;}}}private:int bottom, top; };?
轉載于:https://www.cnblogs.com/heyn1/p/11114940.html
總結
以上是生活随笔為你收集整理的LeetCode-240 Search a 2D Matrix II的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 北风设计模式课程---里氏替换原则(Li
- 下一篇: teXt使用