[剑指Offer]---03数组中重复的数字与04二维数组中的查找

03数组中重复的数字

思路:哈希表,扫描数组里的每个数字,看哈希表里是否有这个数字,没有就将这个数字加进去,有的话,则该数字重复。时间复杂度是O(n)。

class Solution {
public:
    int findRepeatNumber(vector<int>& nums) {

         unordered_set<int>  record;
         for(auto iter=nums.begin();iter!=nums.end();++iter){

            int count=record.count(*iter);
            if(count==0)
            {
                record.insert(*iter);
            }
            else 
            {
               return *iter;
            }
         }

         return -1;

    }
};

 

04二维数组中的查找

思路:

    右上角遍历,时间复杂度O(n+m)

    如果该数字等于要查找的数字,查找过程结束;

    如果该数字大于要查找的数字,剔除这个数字所在的列;

    如果该数字小于要查找的数字,剔除这个数字所在的行

 


class Solution {
public:
    bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {

        if(!matrix.empty())
        {
            // 行列个数
            int row = matrix.size();
            int col = matrix[0].size();
 
            // 右上角坐标
            int x = 0;
            int y = col-1;
 
            while(x<row && y>=0)
            {
                
                if(matrix[x][y] == target)
                    return true;
 
                if(matrix[x][y] < target)
                    ++x;
                else
                    --y;
            }
        }
 
        return false;

    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值