【leetCode】Search a 2D Matrix

来源:互联网 发布:中国网络的发展历程 编辑:程序博客网 时间:2024/06/05 20:44

题目:

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.

中文大意:

写一个高效查找算法在一个m*n的矩阵中查找指定值。这个m*n矩阵拥有以下两个性质:

1、对于每一行,整数都是从左到右递增;

2、对于每一列,整数都是从低到高递增;

举个栗子:对于下面这个矩阵

[  [1,   3,  5,  7],  [10, 11, 16, 20],  [23, 30, 34, 50]]

输入3,返回true;


思路

对每一行进行二分查找.......

class Solution {public:    bool searchMatrix(vector<vector<int>>& matrix, int target) {        for(int i = 0; i < matrix.size();i++)        {            int colSize = matrix[i].size();            //如果这个数大于该行的最小值,小于该行的最大值            if(matrix[i][0]<= target && matrix[i][colSize-1]>=target)            {                 bool j = binaySearch(matrix[i],target);                   if(j)                   return j;            }                }        return false;    }private:/*二分查找算法*/    bool binaySearch(vector<int> a,int target)    {        int length = a.size();    int left = 0, right = length - 1;    int mid = (left + right) / 2;//(0+3)/2 == 1    while (left < right)    {    mid = (left + right) / 2;    if (a[left] == target)    return true;    if (a[right] == target)    return true;    if (a[mid] == target)    return true;    else if (a[mid] < target)    {    left = mid + 1;    continue;    }    else if (a[mid]>target)    {    right = mid;    continue;    }    }    if (left == right && a[left] == target)    {    return true;    }    else    return  false;     }};




0 0
原创粉丝点击